Catch Multiple Custom Exceptions? - C++

If you have multiple exception types, and assuming there's a hierarchy of exceptions (and all derived publicly from some subclass of std::exception,) start from the most specific and continue to more general:

try
{
    // throws something
}
catch ( const MostSpecificException& e )
{
    // handle custom exception
}
catch ( const LessSpecificException& e )
{
    // handle custom exception
}
catch ( const std::exception& e )
{
    // standard exceptions
}
catch ( ... )
{
    // everything else
}

On the other hand, if you are interested in just the error message - throw same exception, say std::runtime_error with different messages, and then catch that:

try
{
    // code throws some subclass of std::exception
}
catch ( const std::exception& e )
{
    std::cerr << "ERROR: " << e.what() << std::endl;
}

Also remember - throw by value, catch by [const] reference.


You should create a base exception class and have all of your specific exceptions derive from it:

class BaseException { };
class HourOutOfRangeException : public BaseException { };
class MinuteOutOfRangeException : public BaseException { };

You can then catch all of them in a single catch block:

catch (const BaseException& e) { }

If you want to be able to call GetMessage, you'll need to either:

  • place that logic into BaseException, or
  • make GetMessage a virtual member function in BaseException and override it in each of the derived exception classes.

You might also consider having your exceptions derive from one of the standard library exceptions, like std::runtime_error and use the idiomatic what() member function instead of GetMessage().