Jason Heine Jason Heine - 1 month ago 6
C++ Question

How to get the error message from a C++ catch(...) block?

So, I'm looking at the C++ reference for the try/catch block.

I see there are a few ways to capture an exception like so:

try {
f();
} catch (const std::overflow_error& e) {
// this executes if f() throws std::overflow_error (same type rule)
} catch (const std::runtime_error& e) {
// this executes if f() throws std::underflow_error (base class rule)
} catch (const std::exception& e) {
// this executes if f() throws std::logic_error (base class rule)
} catch (...) {
// this executes if f() throws std::string or int or any other unrelated type
}


I see in the following examples that you can capture the "e" data like so:

std::cout << e.what();


So my question boils down to this:

How do I get the exception data on the
catch(...)
?

(Side question: is it even wise to use the
catch(...)
?)

Answer

In general, you can not. C++ allows pretty much anything to be thrown. For example throw 42; is perfectly well-defined C++ code, and the exception's type is int.

As for it being wise to use it - there are valid uses:

  • If an exception is thrown and there is no catch block for it all the way up, std::terminate is called and there is no guarantee of stack unwinding. catch(...) guarantees that (because it catches any exception).

int main()
{
    super_important_resource r;
    may_throw();
    // r's destructor is *not* guaranteed to execute if an exception is thrown
}

int main()
try {
    super_important_resource r;
    may_throw();
    // r's destructor is guaranteed to execute during stack unwinding
} catch(...) {
}
  • it's a valid use case to log that an exception was thrown, before rethrowing it.

try {
//...
} catch(...) {
    log() << "Unknown exception!";
    throw;
}