这是post的后续问题。请参阅此问题的结尾,了解“函数尝试块”的定义。为什么我们需要一个函数try块?
问题:如果函数try块没有“处理”在构造函数中引发的异常,为什么我们最终需要它们?你能举一个例子来利用函数try块吗?
考虑下面的代码。
#include <iostream>
#include <new>
#include <exception>
using namespace std;
struct X {
int *p;
X() try : p(new int[10000000000]) {}
catch (bad_alloc &e) {
cerr << "exception caught in the constructor: " << e.what() << endl;
}
};
int main() {
try {
X x;
}
catch (exception &e){
cerr << "exception caught outside the constructor: " << e.what() << endl;
}
return 0;
}
输出是
exception caught in the constructor: std::bad_alloc exception caught outside the constructor: std::bad_alloc
在我看来,无论我在功能try块做,异常总是要被抛出到调用外部范围构造函数,例如上述代码中的X x;
。
“function try block”的定义,摘自“C++ Primer 5th”。
要处理来自构造函数初始值设定项的异常,我们必须将构造函数作为函数try块写入。函数try块允许我们将一组catch子句与构造函数的初始化阶段(或析构函数的销毁阶段)以及构造函数的(或析构函数的)函数体相关联。