Throwing an exception when building an object during a throw?

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 on my cast site:

try {
    throw MyException( NULL );
}
catch( std::exception const& e ) {
    std::cout << e.what();
}

(the code has not been compiled, so please excuse any errors)

I am wondering what will happen when I exit the constructor when building due to another throw. I assume this is legal and catch will catch std::invalid_argumentand the previous exception ( MyException) will be ignored or discarded.

My goal with this design is to enforce invariants in my exception class. message_it should never be NULL, and I do not want the conditions to check if it is null in my overload what(), so I check them in the constructor and throw if they are invalid.

Is this correct or different from behavior?

+3
3

, ( MyException), , . , , .

, , MyException. " , std::terminate".

+4

15.1 n3376

7

, , , , , , std:: terminate (15.5.1).

, , (, ) , . , , terminate().

:

struct C
{
       C() { }
       C(const C&) { throw 0; }
};

int main()
{
  try
  {
    throw C();   // calls std::terminate()
  }
  catch(C) { }
}

terminate , . (15.1.4). ( ) , .

, , , .

  • : A MyException
  • : std::invalid_argument std::invalid_argument
+3

, , . , , , , , .

, catch (...). , , , , , .

, , , . - .

0

All Articles