Search code examples
c++exceptionterminate

exception handling, unexpected terminator in c++


Following code is about exception handling. I got the output:

Botch::f()
I'll be back!

Why Fruit is not caught? Thanks!

Ignore this. I think I have provided enough detail.

#include <exception>
#include <iostream>
using namespace std;

void terminator() {
    cout << "I'll be back!" << endl;
    exit(0);
}

void (*old_terminate)() = set_terminate(terminator);

class Fruit {};

class Botch {
public:
    void f() throw(Fruit, bad_exception) {
        cout << "Botch::f()" << endl;
        throw Fruit();
    }
    ~Botch() { throw 'c'; }
};

int main() {
    try{
        Botch b;
        b.f();
    } catch(Fruit&) {
        cout << "inside catch(Fruit)" << endl;
    } catch(bad_exception&) {
        cout << "caught a bad_excpetionfrom f" << endl;
    }
}

Solution

  • Fruit is not caught because the code never reaches that catch clause. In the try block in main, the call to b.f() throws an exception of type Fruit. In response, the code destroys the Botch object before entering the catch clause. The destructor of Botch throws another exception, and that triggers the call to terminate.