【问题标题】:Detecting whether or not a catch block is being executed检测是否正在执行 catch 块
【发布时间】:2017-04-27 20:00:48
【问题描述】:

我有一个通过现有代码使用的错误记录功能。如果可能,我想通过检测何时从catch 块调用它来改进它,以便在异常可用时从异常中提取其他信息。在 catch 块期间,您可以重新抛出异常并在本地捕获它。

void log_error()
{
    try {
        throw;  // Will rethrow the exception currently being caught
    }
    catch (const std::exception & err) {
        // The exception's message can be obtained
        err.what();
    }
}

如果您不在catch 块的上下文中,此函数将调用std::terminate。我正在寻找一种方法来检测是否存在要重新抛出的异常,调用throw; 是否安全?我找到了std::uncaught_exception,但它似乎只适用于作为抛出异常的一部分而执行的函数,并且在catch 块中是无用的。我已经阅读了http://en.cppreference.com/w/cpp/error,但似乎找不到任何适用的机制。

#include <stdexcept>
#include <iostream>

struct foo {
    // prints "dtor : 1"
    ~foo() { std::cout << "dtor : " << std::uncaught_exception() << std::endl;  }
};

int main()
{
    try
    {
        foo bar;
        throw std::runtime_error("error");
    }
    catch (const std::runtime_error&)
    {
        // prints "catch : 0", I need a mechanism that would print 1
        std::cout << "catch : " << std::uncaught_exception() << std::endl;
    }
    return 0;
}

我发现的解决方法包括简单地实现从catch 块调用的不同函数,但此解决方案不会追溯。另一种方法是使用带有自定义异常类的thread_local 标志来了解当前线程何时构造了异常但没有销毁它,但这似乎容易出错并且与标准和现有异常类不兼容。这种弱解决方法的示例:

#include <exception>

struct my_base_except : public std::exception
{
    my_base_except() { ++error_count; }
    virtual ~my_base_except() { --error_count; }
    my_base_except(const my_base_except &) { ++error_count; }
    my_base_except(my_base_except&&) { ++error_count; }

    static bool is_in_catch() {
        return error_count > 0;
    }

private:
    static thread_local int error_count;
};

thread_local int my_base_except::error_count = 0;

void log_error()
{
    if (my_base_except::is_in_catch())
    {
        // Proceed to rethrow and use the additional information
    }
    else
    {
        // Proceed with the existing implementation
    }
}

是否存在解决此问题的标准功能?如果没有,是否有比我在这里确定的更强大的解决方法?

【问题讨论】:

    标签: c++ exception try-catch


    【解决方案1】:

    std::current_exception 可能就是您要找的。​​p>

    std::current_exception 返回一个std::exception_ptr,它是指向当前处理的异常的指针类型,如果没有处理异常,则返回nullptr。可以使用std::rethrow_exception 重新抛出异常。

    【讨论】:

    • 嗯,这很尴尬。它就在我链接的页面顶部附近。下次我会多注意的!只要计时器允许,我就会接受。
    猜你喜欢
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多