how to get message of catch-all exception [duplicate]

If I want to write useful info to a file whenever i caught a catch-all exception, how to do it?

try
{
   //call dll from other company
}
catch(...)
{
   //how to write info to file here???????
}

You can't get any information out of the ... catch block. That is why code usually handles exceptions like this:

try
{
    // do stuff that may throw or fail
}
catch(const std::runtime_error& re)
{
    // speciffic handling for runtime_error
    std::cerr << "Runtime error: " << re.what() << std::endl;
}
catch(const std::exception& ex)
{
    // speciffic handling for all exceptions extending std::exception, except
    // std::runtime_error which is handled explicitly
    std::cerr << "Error occurred: " << ex.what() << std::endl;
}
catch(...)
{
    // catch any other errors (that we have no information about)
    std::cerr << "Unknown failure occurred. Possible memory corruption" << std::endl;
}

A caught exception is accessible by the function std::current_exception(), which is defined in <exception>. This was introduced in C++11.

std::exception_ptr current_exception();

However, std::exception_ptr is an implementation-defined type, so you can't get to the details anyway. typeid(current_exception()).name() tells you exception_ptr, not the contained exception. So about the only thing you can do with it is std::rethrow_exception(). (This functions seems to be there to standardize catch-pass-and-rethrow across threads.)


There's no way to know anything about the specific exception in a catch-all handler. It's best if you can catch on a base class exception, such as std::exception, if at all possible.