Problem with Exception Inheritance

Hi,

I have been trying to have hierarchies for exception-handling (i.e. base exception class and derived exception classes), as shown:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <cstdio>
#include <exception>
using namespace std;

class TimeException: public exception {
public:
	virtual const char* what() const throw() {
		return "Wrong Time Format";
	}
};

class HourException: public TimeException {
public:
	const char* what() const throw() {
		return "Hour must lies between 0 and 23";
	}
};

struct Hour {
	Hour(int h) {
		if (h < 0 || h >= 24) {
			throw HourException();
		}
		val = h;
	}
	int getHour() { return val; }
	int val;
};

int main() {
	try {
		Hour h(-5);
		printf("%d\n", h.getHour());
	}
	catch (TimeException e) {
		printf("%s\n", e.what());
	}
}


To my belief, when TimeException is being caught during execution, the what function being called will be the HourFunction one because of the presence of virtual keyword in TimeException.

When I try to execute it however, the result is "Wrong Time Format" instead: what function in TimeException is being called instead.

Can anyone let me know what I have coded wrong that has led to such behavior?

Thanks,
Charles (The Newbie)
You need to catch the exception by reference.
catch (TimeException& e) {
Thanks Peter, I have missed the obvious. Thanks so much
Topic archived. No new replies allowed.