TCS
TCS

Reputation: 5900

Exception class that catches many types of other exceptions

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

Answers (2)

Mike Seymour
Mike Seymour

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

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247969

  • first, it is generally a terrible idea to catch every exception type. Generally speaking, if you don't know what the exception is, how can you meaningfully handle when it occurs?
  • second, if you want to catch every exception type, you can use 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).
  • third, even this only catches C++ exceptions. Other errors, such as segmentation faults/access violations won't be caught by this. If you want to catch that kind of errors, you'll need to use platform-specific operations or language extensions.
  • finally, type conversions aren't considered when catching exceptions. If an exception type 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

Related Questions