Roger Dahl
Roger Dahl

Reputation: 15734

Catching boost::exception for logging

I'm using Boost for some in-house codes. In main(), I would like to catch and log all boost::exceptions before exiting the program.

How do I catch boost::exceptions and retrieve the exception information as a string, for logging?

Upvotes: 0

Views: 1832

Answers (1)

Sean Cline
Sean Cline

Reputation: 7199

I recommend that you take a look at boost::diagnostic_information.

Here is an example for you. It is by no means complete and will take some customization to get it to do exactly what you want.

void main()
{
    try
    {
        // Your code that can throw.
    }
    catch (const boost::exception& ex) 
    {
        // Output some debug information.
        std::cerr << boost::diagnostic_information(ex) << std::endl;

        // Here we can choose to perform some graceful-shutdown activities,
        // and/or rethrow the exception, triggering a call to std::terminate().
        throw; // Rethrow.
    }
    catch (const std::exception& ex) 
    {
        // Let's do the same for std::exception just for comparison.
        std::cerr << ex.what() << std::endl;
        throw; // Rethrow.
    }
}

Where you will probably need to customize this:

  • Rethrowing in the main will trigger a std::terminate(). You might want to perform some tasks that more gracefully shutdown your code.

  • std::cerr might not be a great place to send this sort of information for you. Perhaps you want to log it to file. Or perhaps you might want to redirect std::cerr to a file.

  • Your code may have a chance of throwing something that is not a boost::exception or a std::exception. Maybe you want a catch all for that: catch (...)

  • Keep in mind that this is try-catch block only comes into play on the main thread of your application. You will have to do something similar in the entrypoints of any other threads that might throw an exception that is not handled.

  • This is no replacement for proper exception handling throughout your entire application.

Upvotes: 3

Related Questions