Reputation: 671
I was playing around with C++ exceptions, but while writing a program I am not able to explain the output. So my understanding is whenever an exception is thrown the program looks for a matching try block, if there isnt one in the current scope all the stack variables will be destroyed and the caller will be searched for the try block, if a try is encountered a matching catch block is searched.Before moving to the matching catch all the stack variables inside the try block are destroyed. If one catch block is found the exception is handled and the program continues after the catch block. However in the following program I am not getting the output as expected:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Bomb {
int x;
public:
Bomb( ):x(0) {
cout<< "callling constructor " << endl;
}
~Bomb() {
cout<<" Calling destructor " << endl;
throw "boom";
}
void * operator new( size_t size ) throw() {
cout<<" Calling operator new " << endl;
return malloc(size);
}
void operator delete( void * p ) throw() {
cout<<" Calling operator delete " << endl;
if( p != 0 ) free(p);
}
};
void f() {
//Bomb myBomb;
Bomb *pBomb = new Bomb();
try {
delete pBomb;
} catch( ... ) {
cout<< " caught exception " << endl;
}
}
int main( int argc, char ** argv ) {
try {
f();
}
catch( char * message ) {
cout << " caught exception in main " << endl;
}
}
The output is: calling operator new calling constructor calling destructor and then it crashes
I was expecting caught exception.
Am i missing something fundamental ?
Upvotes: 1
Views: 59
Reputation: 16204
It matters a lot whether you are using C++11 or an earlier standard.
In an earlier standard, I believe that what you expected is what would have happened. However in C++11, destructors are implicitly given a noexcept
specification unless you explicitly don't give them this, or unless they have a child member variable whose destructor is not marked noexcept
... (reaches for standard...)
Upvotes: 5