Reputation: 5900
I tried to make an exception class (lets call it EXP) that will be able to catch various types of other exception classes (for instance, std::exception), but without any success. The main problem is that there are many types of exceptions that I need to catch, and I wondered if there is a better way than writing a macro that holds all the possible catches.
What I want to do (if its even possible) is something like that:
class EXP : ?? maybe must inherit ??
{
// EXP implementation
}
EXP is defined in such a way that this is possible:
try
{
throw std::exception("error string");
}
catch(const EXP& e)
{
// catches the exception
}
So if it is possible, how can I define EXP so it will do what I want?
Thanks! :-)
Upvotes: 1
Views: 183
Reputation: 254461
The best approach is to derive all of your exception types from std::exception
(or its standard subtypes such as std::runtime_error
); then you can use catch (std::exception const &)
to catch anything thrown by your code, the standard library, or any other well-behaved library.
Upvotes: 1
Reputation: 247969
catch (...)
. However, this does not directly give you access to the caught exception object. To access the exception object you then have to rethrow and catch
each specific type that you're supporting (this rethrowing and recatching can be done in a separate function, which may be a solution to your question).E
is thrown, then you can only handle it by catching E
or any of its base classes. But you can't, for example, handle it by catching an exception that is constructible from an E
.Note: regarding the rethrowing scheme in the second point, it may not work with pre-standard compilers; e.g. it does not work with Visual C++ 6.0.
Upvotes: 4