Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
构造函数中引发的异常的处理程序是什么? 我是C++异常处理的新手。我心中的规则是 如果在调用链(函数调用堆栈)中未找到异常处理程序,则调用终止函数 处理程序是一个catch{}块_C++_C++11_Exception Handling_Try Catch - Fatal编程技术网

构造函数中引发的异常的处理程序是什么? 我是C++异常处理的新手。我心中的规则是 如果在调用链(函数调用堆栈)中未找到异常处理程序,则调用终止函数 处理程序是一个catch{}块

构造函数中引发的异常的处理程序是什么? 我是C++异常处理的新手。我心中的规则是 如果在调用链(函数调用堆栈)中未找到异常处理程序,则调用终止函数 处理程序是一个catch{}块,c++,c++11,exception-handling,try-catch,C++,C++11,Exception Handling,Try 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() {

然而,我无法理解以下行为

#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;
}
#包括
#包括
使用名称空间std;
结构X{
X()尝试{抛出异常();}
捕获(例外和e){
不能使用:


你有两个例外

struct X {
  X() try { throw exception(); }
  catch (exception &e) {
    cout << "Exception caught in constructor!" << endl;
  }
};
struct X{
X()尝试{抛出异常();}
捕获(例外和e){

cout Related:@MM。非常感谢。我搜索了这个问题,但没有找到。在我个人看来,基类构造函数抛出时是一个更好的例子。有人可能会说,在成员初始化失败的情况下,您可以恢复,但不能从对象的不完全初始化中恢复。您能在回答中帮助我回答以下问题吗目前,用户Kerrek SB表示“永远不要使用函数try块。”
X() {
    try { throw exception(); }
    catch (exception &e) {
        cout << "Exception caught in constructor!" << endl;
    }
}
struct X {
  X() try { throw exception(); }
  catch (exception &e) {
    cout << "Exception caught in constructor!" << endl;
  }
};