异常被捕获两次
Exception is caught twice
class A{
public:
A() { throw string("exception A"); };
};
class B{
A a;
public:
B() try : a() {} catch(string& s) { cout << &s << " " << s << endl; };
};
int main(){
try{
B b;
}catch(string& s){
cout << &s << " " << s << endl;
}
return 0;
}
输出为:
0x32c88 exception A
0x32c88 exception A
既然异常已经在B
的构造函数中被捕获,为什么它仍然出现在主函数中?
当 contol 流到达构造函数的函数尝试块的处理程序末尾时,捕获的异常将自动重新引发。
不能禁止在派生类构造函数中构造基类或成员期间引发的异常,因为这将导致构造派生对象具有构造失败的基或成员。
这个GOTW是相关的:http://www.gotw.ca/gotw/066.htm
根据ISO/IEC 14882:2011 15.3 [except.handle]/15:
如果控件到达构造函数或析构函数的函数 try-block 的处理程序的末尾,则会重新引发当前处理的异常。[...]
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- C++两次定义相同的函数会导致错误
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 异常被捕获两次
- 异常从具有函数 try-block 的构造函数中引发两次
- 为什么这条线路运行了两次,而且有异常行为
- 为什么在抛出异常时析构函数调用两次
- 为什么异常的析构函数被调用两次