This is cited from Stroustrup third edition
void f () throw (x2 , x3 )
{
// stuff
}
is equivalent to:
void f ()
try
{
// stuff
}
catch (x2) {throw; } / / rethrow
catch (x3) {throw; } / / rethrow
catch (...) {
std: :unexpected() ; / / unexpected() will not return
}
Now take a look at the following code:
#include <iostream>
#include <string>
using namespace std;
class MyFEx
{
string exMsg_;
public:
MyFEx( string exMsg ): exMsg_(exMsg) {}
void print() { cout<<endl<<exMsg_<<endl; }
};
class MySEx
{
string exMsg_;
public:
MySEx( string exMsg ): exMsg_(exMsg) {}
void print() { cout<<endl<<exMsg_<<endl; }
};
void A(int x) throw ( MyFEx , MySEx )
{
x < 0 ? throw MyFEx( "myfirst " ) : throw MySEx( "mysecond" );
}
void B(int x) throw ( MySEx )
{
A(x);
}
void MyUnexpectedHandler()
{
cout<<"OK, HANDLER CALLED"<<endl;
}
int main( int argc, char* argv[] )
{
unexpected_handler theOldOne = set_unexpected( MyUnexpectedHandler );
try
{
B(-1);
}
catch(MyFEx& ex)
{
ex.print();
}
catch( MySEx& ex)
{
ex.print();
}
cout<<"ok, got here"<<endl;
int i;
cin>>i;
}
Ok, as I noticed the MSVC compiler, doesn't respect the standard, so don't bother compiling with it. It will compile but the result is that MyFEx will be cought in main althow B doesn't specify that it might throw a MyFEx, and the std::unexpected() handler is not even called.
If compiled with gcc the result is almost what I excpected:
B doesn't specify that it might throw a MyFEx exception so the std::unexpected is called with my handler. All my handler does is print a message. What I don't understand is why after the hander is executed std::terminate is still called?
If things would go as Stroustrup says B woudl be equivalent to:
void B(int x)
{
try{
A(x);
}
catch( MySEx )
{
throw;
}
catch(...)
{
std::unexpected();
}
}
since my implementation of the unexpected handler doesn't terminate the program B should return and execution of main should continue normal. Can someone plz explain this strange behaviour?
thx in advance.