Jump to

v07-l2-findOutput4

What is the output of the following code ?

#include <iostream>
using std::cout, std::endl;

class Exception {};
class ChildException : public Exception {};

int main() {
    try {
        throw ChildException()
    }
    catch (Exception&) {
        cout << "Exception" << endl;
    }
    catch (ChildException&) {
        cout << "ChildException" << endl;
    }
    catch (...) {
        cout << "Unknown exception" << endl;
    }
}

???

In the try block, a ChildException is thrown. So each catch blocks are tested in the order they are written, which means that first the program checks if the thrown object can be interpreted as Exception&, which is the case since ChildException is derived from Exception, hence shares its type.

So the first catch block is activated, and the other ignored, hence the program prints Exception in the console.