捕获boost ::日志记录的异常

时间:2013-01-01 17:44:26

标签: exception logging boost

我正在使用Boost来处理一些内部代码。在main()中,我想在退出程序之前捕获并记录所有boost :: exceptions。

如何捕获boost :: exceptions并将异常信息作为字符串检索,以便记录?

1 个答案:

答案 0 :(得分:2)

我建议您查看boost::diagnostic_information

以下是您的示例。它绝不是完整的,并且会进行一些自定义以使其完全符合您的要求。

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.
    }
}

您可能需要自定义此内容:

  • 在主中重新启动会触发std::terminate()。您可能希望执行一些更优雅地关闭代码的任务。

  • std::cerr可能不是发送此类信息的好地方。也许您想将其记录到文件中。或许您可能想要redirect std::cerr to a file

  • 您的代码可能会抛出非boost::exceptionstd::exception的内容。也许你想得到一切:catch (...)

  • 请记住,这是try-catch块仅在您的应用程序的主线程上发挥作用。您将不得不在可能引发未处理的异常的任何其他线程的入口点中执行类似的操作。

  • 在整个应用程序中,这不能替代正确的异常处理。

相关问题