Thread: Throwing exceptions with constructors

  1. #1
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Location
    Australia
    Posts
    986

    Throwing exceptions with constructors

    Hey

    A while ago I raised a question about how Exceptions work. One thing I didn't ask though is what would happen if I threw an exception with the constructor of a class.

    For example, I have a class that reads a configuration file when the program starts up. If I was to put the fil reading part all in the constructor, and throw an exception if the file can't be found/read, could I catch that exception and alert the user theres no file and shut down the program?

    I was wondering this because I was told that constructors can't return a value, so this led me to thinking about exceptions. I'm just worried that maybe if I throw an exception with a constructor the class might not be created properly.

    So what I'm asking is, is it safe to throw exceptions with constructors?

  2. #2
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    Have you tried it, and if so, did it work at all?
    [email protected]
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  3. #3
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    I'm not sure about the absolute safety of doing that but several APIs employ this method. However, I tend to stray away from it because if an object cannot be created you can always check the pointer via code which is outside of the class definition. Exiting classes willy nilly by using exceptions and catching them elsewhere does not set well with me. Some APIs will create an exception object (from an exception class) rather than just have an exception lying out there somewhere to catch which seems a bit more in tune to me.

    But perhaps I'm wrong on this one.

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    If you throw an exception as part of a constructor then the constructor will not finish, therefore the object is not in a "constructed state" and can not be used (the destructors for member objects and base objects will be called, but your destructor will not).

  5. #5
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Location
    Australia
    Posts
    986
    Ahh ok, so what would you say about throwing exceptions when I know that the class will not be used, so all we want to do is show a message box to the user telling them of the error, and exciting the program? I think this would be ok, because I have no need for the class if I can't read the config file, what do you guys think?

  6. #6
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    If you are wanting to put error detection into the definition of your class then I don't see anything wrong with it. The very old OWL libraries used to throw exceptions when a window could not be created and it worked well, although quite annoying.

    But you could also just tell the person that uses the library/class to check the validity of the pointer or object before they use it. That seems more like the responsibility of the person using the class than the one who designed it. But again, just my opinion.

  7. #7
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Just read your post again. If you are trying to open a file in the constructor of the class and that file does not exist then throwing an exception will both stop the object from being created and will notify the programmer what went wrong.

    Let me see if I can think of a better way to handle this situation. It is a bit tricky since there is no way to let the calling code know that the constructor failed to open the file - or that is how it appears to me. But who am I? I've been wrong before.


  8. #8
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Location
    Australia
    Posts
    986
    Yeah, I guess it would be easier if I just didn't worry about reading the file in the constructor and simply created another function inside the class to read it, and that could return something telling me it didn't work.

    But I guess I'm just looking for an excuse to try out these exceptions in a project. It would be easier for a client to call an extra function and check its result rather than to use a try..catch statement.

    Or I could take a reference in the constructors arguments for a place to store the result if the file couldn't be opened.

  9. #9
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    I read the FAQ concerning exceptions and perhaps you might want to if you have not already. They keep expanding the thing so a re-read never hurts.

    But I'm still not a fan of the exceptions, at least not a fan of just throwing them out there waiting for someone to catch them. Perhaps an exception class would be better - when an exception is thrown you could create the exception object and use its member functions to get more details about the exception class, type, and code. It does seem quite robust for error handling, but it also looks as though it could be severely misused.

  10. #10
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Location
    Australia
    Posts
    986
    Yeah, it looks like its going to be one of those things I've read about but won't really use for quite a while in anything big. Just like class inheritance. I've read tonnes on the stuff and I'd love to use it, but the projects I do never seem to warrant its use (and would be much more complex and harder to manage if they did).

    Oh well.

    Thanks very much everyone!

  11. #11
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Originally posted by Bubba
    But I'm still not a fan of the exceptions, at least not a fan of just throwing them out there waiting for someone to catch them. Perhaps an exception class would be better - when an exception is thrown you could create the exception object and use its member functions to get more details about the exception class, type, and code. It does seem quite robust for error handling, but it also looks as though it could be severely misused.
    When I'm using exceptions I always derive them from std::exception and overide virtual const char * what () const throw () . That way you can always catch a std::exception reference and with polymorphism, you can tell what the exception was, but if it's a natural exception like std::bad_alloc, I'm covered for that as well.

  12. #12
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Location
    Australia
    Posts
    986
    Originally posted by Fordy
    When I'm using exceptions I always derive them from std::exception and overide virtual const char * what () const throw () . That way you can always catch a std::exception reference and with polymorphism, you can tell what the exception was, but if it's a natural exception like std::bad_alloc, I'm covered for that as well.
    Hehe.... yeah, thats just what I was thinking....

    *Bows down to Fordys ability to use words like that, and realises he has a very long way to go*

  13. #13
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Code:
    #include <iostream>
    #include <exception>
    #include <string>
    
    class MyException : public std::exception
    {
    	std::string m_str;
    public:
    	const char *what () const throw ()
    	{
    		return m_str.c_str();
    	}
    	MyException(const char *str):m_str(str){}
    };
    
    void foo()
    {
    	throw MyException("Some Dumb Exception");
    }
    
    int main()
    {
    	try
    	{
    		foo();
    	}
    	catch(std::exception& e)
    	{
    		std::cout << "Exception caught" << std ::endl;
    		std::cout << e.what();
    	}
    
    }

  14. #14
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    And yes, constructors are perfect examples of where to throw exceptions. If you can't construct the object, it is imperative that the calling code know about it; exceptions are the logical way to do this.

    One thing, though -- if you're allocating memory via new or new[], you can have exception problems. It's as true in constructors as it is anywhere else. E.g. say you have this:

    Code:
    MyClass::MyClass{
      myObjPtr1 = new MyObject();
      myObjPtr2 = new MyObject();
    }
    If the second construction throws (the object that will be pointed at by myObjPtr2), then we leak memory because the first object is never deleted. A better way is to use smart pointers. Check out Boost. They have several classes of smart pointers. The following code is 100% exception safe:

    Code:
    MyClass::MyClass{
      myObjSharedPtr1 = boost::shared_ptr(new MyObject());
      myObjSharedPtr2 = boost::shared_ptr(new MyObject());
    }
    Exceptions are highly useful, and also highly misunderstood I'm afraid. Exception safety took a long time for even the most brilliant programmers to understand and define, but it's well known by now.
    Last edited by Cat; 07-08-2003 at 09:28 AM.

  15. #15
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Following on from Cat, if you want good info on exception handling, search on the web for Guru of the Week. There's some neat excercises there to give insight into handling exceptions in different circumstances

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about constructors and exceptions
    By Elkvis in forum C++ Programming
    Replies: 3
    Last Post: 12-05-2008, 06:15 PM
  2. Exceptions and constructors
    By Mostly Harmless in forum C++ Programming
    Replies: 2
    Last Post: 06-12-2007, 11:20 AM
  3. Need advice: catch exceptions or call methods to check bits?
    By registering in forum C++ Programming
    Replies: 1
    Last Post: 10-03-2003, 01:49 PM
  4. Copy constructors and private constructors
    By Eibro in forum C++ Programming
    Replies: 5
    Last Post: 11-24-2002, 10:16 AM
  5. Excaption in Derived Constructors?
    By Davros in forum C++ Programming
    Replies: 6
    Last Post: 10-30-2002, 10:01 AM