异常是否可以自动提供有关其环境的详细信息

Can exceptions automatically provide details about their environment?

本文关键字:环境 详细信息 提供有 是否 异常      更新时间:2023-10-16

我想做什么:

struct A
{
    void f()
    {
        throw auto_exception("something went wrong");
    }
}
class Foo
{
    void bar()
    {
        throw auto_exception("step 2 failed");
    }
}

异常的what()字符串应分别读取:

"Exception in A::f(). something went wrong"
"Exception in Foo::bar(). step 2 failed"

这可能吗?

假设您的C++编译器支持__FUNCTION__(或C++11中的__func__),您可以将AUTO_EXCEPTION定义为:

#define AUTO_EXCEPTION( msg ) std::runtime_error( std::string(__FUNCTION__) + ": " + msg )

我真的不会把你想要的东西称为"关于环境的信息"。你可以把它与__FILE__宏和__LINE__宏以及__func__(或者__PRETTY_FUNCTION__在GCC中,或者查看编译器手册以获取其他合适的扩展)拼凑在一起。

可能更有趣的是动态环境,例如引发异常的点的执行跟踪。你可以在运行时使用像libunwind这样的库生成它们。生成跟踪的成本相当高,但由于您仅在发生异常时才执行此操作,因此应该没问题。