Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

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; 
       }
    }

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

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

like image 300
cpp_noname Avatar asked Oct 30 '13 15:10

cpp_noname


1 Answers

Function-try-blocks in a constructor cannot prevent exceptions. Once an exception occurs in a constructor, you have no object, and the exception must propagate. The only thing the function-try-block can do is some local clean-up.

Constructors are indeed a very special animal with regards to function-try-blocks.

Cf. C++11 15.3/14:

The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.


Tl;dr: Do not use function-try-blocks, ever.

like image 60
Kerrek SB Avatar answered Sep 23 '22 15:09

Kerrek SB