我是 C++ 异常处理的新手。我心中的规则是,
- 如果没有找到异常处理程序调用链(函数调用的堆栈),然后终止函数被调用。
- 处理程序是一个catch {} block.
但是,我无法理解以下行为。
#include <iostream>
#include <exception>
using namespace std;
struct X {
X() try { throw exception(); }
catch (exception &e) {
cout << "Exception caught in constructor!" << endl;
}
};
int main() {
try {
throw exception();
}
catch (exception &e) {
cout << "Exception caught in function." << endl;
}
cout << "After Exception being caught in function" << endl;
try {
X x;
}
catch (exception &e) {
cout << "Why exception is caught again!" << endl;
}
return 0;
}
输出是
Exception caught in function.
After Exception being caught in function
Exception caught in constructor!
Why exception is caught again!
问题一:看起来 X 的构造函数中抛出的异常被捕获(或处理)了两次。或者为什么构造函数后面的 catch{} 块不被算作构造函数中异常的处理程序?
如果我不放X x;
in the try{}
阻止并抓住它main()
,输出为:
Exception caught in function.
After Exception being caught in function
Exception caught in constructor!
terminate called after throwing an instance of 'std::exception'
what(): std::exception
Aborted (core dumped)
问题2:当我们没有时调用默认的终止()函数X x;
在 try 块中?
With:
X() try { throw exception(); }
catch (exception &e) {
cout << "Exception caught in constructor!" << endl;
}
X
对象尚未完全构造,因此 catch 不能忽略异常,而应重新抛出异常。
IMO,更清楚什么时候X
有一个成员抛出...(X() try : member(0) {} catch(exception&) {}
).
请注意,您可以使用normal在构造函数块内尝试 catch:
X() {
try { throw exception(); }
catch (exception &e) {
cout << "Exception caught in constructor!" << endl;
}
}
这更自然。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)