cpp*_*ame 5 c++ constructor exception-handling exception try-catch
为什么从类A的构造函数抛出的以下异常会被捕获两次,首先是构造函数本身内的catch,第二次是main函数中的catch?
为什么它不会被构造函数中的catch捕获一次?
#include <iostream>
using namespace std;
class E {
public:
const char* error;
E(const char* arg) : error(arg) { }
};
class A {
public:
int i;
A() try : i(0) {
throw E("Exception thrown in A()");
}
catch (E& e) {
cout << e.error << endl;
}
};
int main() {
try {
A x;
}
catch(...)
{
cout << "Exception caught" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我删除main函数中的try-catch块,程序将崩溃.这是输出:
Exception thrown in A()
terminate called after throwing an instance of 'E'
zsh: abort (core dumped) ./main
Run Code Online (Sandbox Code Playgroud)
为什么在主函数中没有try-catch块时它会崩溃?
这似乎合乎逻辑。考虑以下两个场景。
我。Try 块位于构造函数体内:
A() : i(0) {
try
{
throw E("Exception thrown in A()");
}
catch (E& e) {
cout << e.error << endl;
}
// If code reaches here,
// it means the construction finished well
}
Run Code Online (Sandbox Code Playgroud)
二. Try 块位于初始化构造函数中:
A() try : i(0) {
throw E("Exception thrown in A()");
}
catch (E& e) {
cout << e.error << endl;
// OK, you handled the exception,
// but wait you didn't construct the object!
}
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,发生异常后,您将在构造函数内对其进行处理,然后正确构造对象。
在第二种情况下,发生异常后您将在那里处理它。但是您还没有构造对象,并且调用方没有对象。调用者应该处理未构造的对象情况。