how to catch unknown exception and print it

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.


In C++11 you have: std::current_exception

Example code from site:

#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>

void handle_eptr(std::exception_ptr eptr) // passing by value is ok
{
    try {
        if (eptr) {
            std::rethrow_exception(eptr);
        }
    } catch(const std::exception& e) {
        std::cout << "Caught exception \"" << e.what() << "\"\n";
    }
}

int main()
{
    std::exception_ptr eptr;
    try {
        std::string().at(1); // this generates an std::out_of_range
    } catch(...) {
        eptr = std::current_exception(); // capture
    }
    handle_eptr(eptr);
} // destructor for std::out_of_range called here, when the eptr is destructed

If you use ABI for gcc or CLANG you can know the unknown exception type. But it is non standard solution.

See here https://stackoverflow.com/a/24997351/1859469


Try as suggested by R Samuel Klatchko first. If that doesn't help, there's something else that might help:

a) Place a breakpoint on the exception type (handled or unhandled) if your debugger supports it.

b) On some systems, the compiler generates a call to an (undocumented?) function when a throw statement is executed. to find out, what function that is for your system, write a simple hello world program, that throws and catches an exception. start a debugger and place a breakpoint in the exceptions constructor, and see from where it is being called. the caling function is probably something like __throw(). afterwards, start the debugger again with the program you want to investigate as debuggee. place breakpoint on the function mentioned above (__throw or whatever) and run the program. when the exception is thrown, the debugger stops and you are right there to find out why.

Tags:

C++

Exception