【问题标题】:Catching boost::exception for logging捕获 boost::log 异常
【发布时间】:2013-01-01 17:44:26
【问题描述】:

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

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

【问题讨论】:

    标签: exception logging boost


    【解决方案1】:

    我建议你看看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 块仅在应用程序的主线程上发挥作用。您必须在可能引发未处理异常的任何其他线程的入口点执行类似操作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      相关资源
      最近更新 更多