异常从具有function-try-block的构造函数中抛出两次 [英] An exception gets thrown twice from a constructor with a function-try-block

查看:277
本文介绍了异常从具有function-try-block的构造函数中抛出两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么从A类的构造函数抛出的以下异常被捕获两次,首先是在构造函数内部的catch,第二次是在main函数中的catch?

Why does the following exception thrown from the constructor of class A get caught twice, first by the catch within the constructor itself and second time by the catch in the main function?

为什么它不会被构造函数中的catch捕获一次?

Why doesn't it get caught just once by the catch within the constructor?

 #include <iostream>
    using namespace std;

    class E {
       public:
          const char* error;
          E(const char* arg) : error(arg) { }
    };

    class A {
       public:
          int i;

          A() try : i(0) {
             throw E("Exception thrown in A()");
          }
          catch (E& e) {
             cout << e.error << endl;
          }
    };

    int main() {

       try {
          A x;
       }
       catch(...) 
       {
        cout << "Exception caught" << endl; 
       }
    }



如果我删除了try-catch块函数,程序将崩溃。
下面是输出:

If I remove the try-catch block in the main function, the program will crash. Here is the output:

Exception thrown in A()
terminate called after throwing an instance of 'E'
zsh: abort (core dumped)  ./main

没有在main函数中的try-catch块?

Why does it crash without the try-catch block in the main function?

推荐答案

请考虑以下两种情况。

i。 try块是在构造函数的内部:

i. Try block is inside constructor's body:

  A() : i(0) {
    try
    {
       throw E("Exception thrown in A()");
    }
    catch (E& e) {
       cout << e.error << endl;
    }
    // If code reaches here,
    // it means the construction finished well
  }

ii。 Try块是在初始化方法ctor:

ii. Try block is in initializer ctor:

  A() try : i(0) {
     throw E("Exception thrown in A()");
  }
  catch (E& e) {
     cout << e.error << endl;

     // OK, you handled the exception,
     // but wait you didn't construct the object!
  }

在第一种情况下,在异常之后,然后你将正确地构造对象。

In the first case, after an exception, you will handle it inside the constructor and then you will construct the object properly.

在第二种情况下,在异常之后你会处理它。 您尚未构建对象,并且您在调用方没有对象。调用者应该处理一个未构造的对象情况。

In the second case, after an exception you will handle it there. BUT you didn't construct the object yet and you have no object in the caller's side. The caller should handle an un-constructed object situation.

这篇关于异常从具有function-try-block的构造函数中抛出两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆