C++ 检测是否正在执行catch块
我有一个通过现有代码使用的错误日志功能。如果可能,我想通过检测何时从C++ 检测是否正在执行catch块,c++,exception,try-catch,C++,Exception,Try Catch,我有一个通过现有代码使用的错误日志功能。如果可能,我想通过检测何时从catch块调用它来改进它,以便在异常可用时从异常中提取附加信息。在catch块期间,您可以重新显示异常并在本地捕获它 void log_error() { try { throw; // Will rethrow the exception currently being caught } catch (const std::exception & err) {
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是否安全代码>?我发现,但它似乎只适用于作为抛出异常的一部分执行的函数,在catch
块中没有用处。我通读了一遍,但似乎找不到任何适用的机制
#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;
}
是否存在解决此问题的标准功能?如果没有,是否有比我在这里确定的更可靠的解决方案?可能是您正在寻找的
std::current_exception
返回一个std::exception_ptr
,它是指向当前处理的异常的指针类型,如果没有处理异常,则返回nullptr
。例外情况可以通过重新调用。好吧,那太尴尬了。它就在我链接的页面顶部附近。下次我会更加注意的!只要计时器允许,我就接受。
#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
}
}