gpt4 book ai didi

c++ - 异常处理相关

转载 作者:行者123 更新时间:2023-11-28 00:58:07 25 4
gpt4 key购买 nike

I am trying to call terminate function. [I think this function gets called when another exception arises during stack unwinding]. The same scenario I have written and trying to verify.

I am able to see a call being made to terminate() function but i am not sure why i am geting the Debug Error.

While trying to execute the following code in Visual studio 2008, I am getting an error message dialog box "Debug Error". The output is also being displayed:

Output:

In try block

In constructor of A

In constructor of B

In destructor of B

In destructor of A

Call to my_terminate

Why this "Debug Error" window appears while executing this code? It is expected behavior? How to remove this error?

class E
{
public:
const char* message;
E(const char* arg) : message(arg) { }
};
void my_terminate()
{
cout << "Call to my_terminate" << endl;
};

class A
{
public:
A() { cout << "In constructor of A" << endl; }
~A()
{
cout << "In destructor of A" << endl;
throw E("Exception thrown in ~A()");
}
};

class B
{
public:

B() { cout << "In constructor of B" << endl; }
~B() { cout << "In destructor of B" << endl; }
};

void main()
{
set_terminate(my_terminate);

try
{
cout << "In try block" << endl;
A a;
B b;
throw("Exception thrown in try block of main()");
}
catch (const char* e)
{
cout << "Exception: " << e << endl;
}
catch (...)
{
cout << "Some exception caught in main()" << endl;
}

cout << "Resume execution of main()" << endl;
getch();
}

最佳答案

您正在从 ~A() 中抛出异常。从析构函数中抛出异常是危险的。如果另一个异常已经在传播,则应用程序将终止。参见 https://stackoverflow.com/a/130123/72178以获得更详细的描述。

Why this "Debug Error" window appears while executing this code?

您正在 try block 中的 main 中抛出异常。这会调用“堆栈展开”并调用 AB 的析构函数。当 ~A() 抛出异常时,应用程序终止。

It is expected behavior?

是的,它是由标准定义的。

How to remove this error?

不要从析构函数中抛出。

关于c++ - 异常处理相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052664/

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