Throwing an exception while constructing object during a throw?

c++, exception

Solution

The object you intend to throw (in this case `MyException`) must be successfully constructed before it can be thrown. So you're not throwing it yet, since it hasn't been constructed.

So this will work, throwing the exception from within `MyException`'s constructor. You won't trigger the "throwing an exception while handling an exception causes `std::terminate`" issue.

Problem

I have an exception class: ``` class MyException : public std::exception { public: MyException( char* message ) : message_( message ) { if( !message_ ) throw std::invalid_argument("message param must not be null"); } }; ``` And at my throw site: ``` try { throw MyException( NULL ); } catch( std::exception const& e ) { std::cout << e.what(); } ``` (code was not compiled, so please excuse any errors) I'm wondering what will happen when I throw from a constructor while constructing due to another throw. I assume this is legal, and the catch will end up catching a `std::invalid_argument`, and the previous exception thrown (`MyException`) will be ignored or cancelled out. My goal with this design is to enforce invariants in my exception class. `message_` should never be NULL, and I don't want to have if conditions to check if it is null in my `what()` overload, so I check them in the constructor and throw if they are invalid. Is this correct, or is the behavior different?

Original source