An exception gets thrown twice from a constructor with a function-try-block

后端 未结 3 1702
眼角桃花
眼角桃花 2021-01-05 20:13

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 th

3条回答
  •  不知归路
    2021-01-05 20:48

    It seems logical. Consider two following scenarios.

    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 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.

提交回复
热议问题