<< PreviousNext >>

Exceptions and inheritance

I recently played around with exception handling in C++ and realized that it did not work as I thought it did. Since I usually catch exceptions by const reference, the problem is mostly based on this.

The given code contains four functions throw0 to throw3, and the goal is to realize what will be thrown. The main function will run each of these and output the exception it caught by reference. So, what will the output be?

exception.cpp

#include <iostream>
#include <exception>

using namespace std;

/**
 * Our own base-class for exception to better see what is happening.
 */
class Exception {
public:
	virtual const char *what() const {
		return "unknown";
	}
};

class A : public Exception {
public:
	virtual const char *what() const {
		return "A";
	}
};

// Throw an exception from a reference.
void throw0() {
	A a;
	Exception &e = a;
	throw e;
}

// Catch an exception by the base-class and then re-throw it.
void throw1() {
	try {
		throw A();
	} catch (const Exception &e) {
		throw e;
	}
}

// Catch an exception and re-throw it.
void throw2() {
	try {
		throw A();
	} catch (...) {
		throw;
	}
}

// Can we re-throw from another function?
void handle() {
	throw;
}

void throw3() {
	try {
		throw A();
	} catch (...) {
		handle();
	}
}

// Test it.
int main() {

	try {
		throw0();
	} catch (const Exception &e) {
		cout << "throw0: " << e.what() << endl;
	}

	try {
		throw1();
	} catch (const Exception &e) {
		cout << "throw1: " << e.what() << endl;
	}

	try {
		throw2();
	} catch (const Exception &e) {
		cout << "throw2: " << e.what() << endl;
	}

	try {
		throw3();
	} catch (const Exception &e) {
		cout << "throw3: " << e.what() << endl;
	}

	return 0;
}

Download files

Answer and comments