【发布时间】:2014-05-20 06:56:26
【问题描述】:
我是 C++ 异常处理的新手。我心目中的规则是,
- 如果在调用链(函数调用堆栈)中没有找到异常处理程序,则调用终止函数.
- 处理程序是一个 catch {} 块。
但是,我无法理解以下行为。
#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!
问题 1: 似乎 X 的构造函数中抛出的异常被捕获(或处理)了两次。或者为什么构造函数后面的 catch{} 块不计为构造函数中异常的处理程序?
如果我不将X x; 放在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: 当我们在 try 块中没有 X x; 时,是否会调用默认的 terminate() 函数?
【问题讨论】:
-
@MM。非常感谢。我搜索但错过了那个问题。
标签: c++ c++11 exception-handling try-catch