Overriding std::exception

M

Miles

Hello all,

When I subclass std::exception and throw an instance of the subclass,
when I call the what() method of the caught exception, it does not
call the overridden method. I'm under the impression that
std::exception declares what() as a virtual method, so I'm at a loss
as to why the subclass's what() is not being called. For example, for
this program:

#include <exception>
#include <iostream>
#include <stdexcept>

class Exception1 : public std::exception {
public:
Exception1() {}
virtual ~Exception1() throw() {}
virtual const char *what() { return "* Exception1 what"; }
};

class Exception2 : public Exception1 {
public:
Exception2() {}
virtual ~Exception2() throw() {}
virtual const char *what() { return "* Exception2 what"; }
};

int main() {
try {
throw Exception2();
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
try {
throw Exception2();
} catch (Exception1 &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}

I get the output:

10Exception2
* Exception2 what

I expect to see
* Exception2 what
* Exception2 what

I'm seeing this on gcc v4 on two different platforms, so it seems
intentional. Could anyone explain this to me, and what I need to do
to get the expected behavior (besides just using my own base class)?

Thanks,
Miles
 
M

Miles


Thank you for your response, but that doesn't explain what I'm
seeing. The FAQ entry is about throwing a reference to an object when
the apparent type of an object is different from its actual type at
the point at which it is thrown. I know that an object of the correct
type is being thrown, because std::exception::what returns the
typeid().name() of the object of the correct class.

try {
throw Exception2();
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}

In that catch block, e is a reference to an Exception2 object (I've
verified this with typeid()), but its what() method is not being
called--it is behaving as if what() were not virtual, but according to
everything I can find, std::exception::what() *is* virtual.

Thanks,
Miles
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top