gpt4 book ai didi

c++ - cpp异常获取抛出调用者的详细信息

转载 作者:太空狗 更新时间:2023-10-29 21:33:40 29 4
gpt4 key购买 nike

我有一些自定义异常,如下所示

class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;

void testException(){
throw myex;
}

void doSomething2(){
testException();
}
void doSomething1(){
doSomething2();
}


int main () {
try
{
doSomething1();
}
catch (exception& e)
{
cout << e.what() << '\n';
}
return 0;
}

所以在 main 函数中我无法知道 throw 的调用者(哪个函数抛出异常),如何获取详细信息?

最佳答案

据我所知,在 C++ 中没有简单的可移植方法可以做到这一点。有一些相当复杂的方法可以使用特定于操作系统的调用来获取完整的堆栈跟踪。

我用来获取异常来源的最简单方法是使用 MACROS。

不推荐在可以避免的地方使用宏,但这是它们被证明有用的少数几个地方之一。

我倾向于使用比这稍微复杂的东西,但这是它的基础:

#ifndef NDBUG
#define throw_runtime_error(msg) \
throw std::runtime_error(std::string(msg) \
+ " line: " + std::to_string(__LINE__) \
+ " file: " + std::string(__FILE__))
#else
#define throw_runtime_error(msg) throw std::runtime_error(msg)
#endif

void doSomething2(){
throw_runtime_error("My runtime error.");
}
void doSomething1(){
doSomething2();
}

int main()
{
try
{
doSomething1();
}
catch(std::exception const& e)
{
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}

return EXIT_SUCCESS;
}

您不会获得完整的跟踪记录,但您确实可以看到抛出异常的位置。 MACRO 仅在 NDBUG 未设置时包含调试信息,因为 release 构建应设置该宏以禁用调试信息。

关于c++ - cpp异常获取抛出调用者的详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50527370/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com