Exception specification

In Java exception specification is a mandatory part of method declaration. In C++ exception specification is optional. When it is used, the behaviour is different, than in Java.


class E1;
class E2;

void f() throw(E1)  // throws only E1 or subclasses
{
...
throw E1();     // throws exception of type E1
...
throw E2();     // calls unexpected() which calls terminate()
}

// same as:
void f()
try {
...
}
catch(E1)  { throw; }
catch(...) { std::unexpected(); }


//============================================

class E1;
class E2;

void f() throw(E1,std::bad_exception)  // throws only E1 or subclasses
{                                      // or bad_exception 
...
throw E1();     // throws exception of type E1
...
throw E2();     // calls unexpected() which throws bad_exception
}


typedef void (*unexpected_handler)();
unexpected_handler set_unexpected(unexpected_handler);

typedef void (*terminate_handler)();
terminate_handler set_terminate(terminate_handler);

// terminate() by default calls abort()


void f() throw()  { }    // can improve efficiency


//=============================================



~T::T()
{
if ( ! uncaught_exception() )
{
// code that could throw...
}
else
{
// code must not throw
}
}