How to catch and print an exception of unkown type

If it derives from std::exception you can catch by reference:

try
{
    // code that could cause exception
}
catch (const std::exception &exc)
{
    // catch anything thrown within try block that derives from std::exception
    std::cerr << exc.what();
}

But if the exception is some class that has is not derived from std::exception, you will have to know ahead of time it’s type (i.e. should you catch std::string or some_library_exception_base).

You can do a catch all:

try
{
}
catch (...)
{
}

but then you can’t do anything with the exception.

Leave a Comment