检测是否正在执行catch块

时间:2017-04-27 20:00:49

标签: c++ exception try-catch

我有一个错误记录功能,它通过现有代码使用。如果可能的话,我想通过检测从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
    }
}

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

1 个答案:

答案 0 :(得分:3)

std::current_exception可能就是你要找的东西。

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

相关问题