9

Consider the following C++ program

struct str
{
       int mem;
       str()
       try
          :mem(0)
       {
               throw 0;
       }
       catch(...)
       {
       }
};

int main()
{
       str inst;
}

The catch block works, i.e. the control reaches it, and then the program crashes. I can't understand what's wrong with it.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • Additional answers here: http://stackoverflow.com/questions/27921250/constructor-as-a-function-try-block-exception-aborts-program – Brent Bradburn Feb 23 '15 at 23:36

1 Answers1

17

Once the control reaches the end of the catch block of function-try-block of a constructor, the exception is automatically rethrown. As you don't catch it further in main(), terminate() is called. Here is an interesting reading: http://www.drdobbs.com/184401316

usta
  • 6,699
  • 3
  • 22
  • 39
  • Thanks a lot. Is it rethrown only in constructor or in other functions too? – Armen Tsirunyan Oct 08 '10 at 08:38
  • @Armen Tsirunyan: You're welcome ;) Only in constructor. That all is explained very well in the link above. – usta Oct 08 '10 at 08:43
  • The same thing happens if you use a function-try-block in a destructor. The article mentions that too. – Brent Bradburn Feb 17 '11 at 07:38
  • @nobar: Yes, that's right. I was answering to "Is it rethrown only in constructor or in other functions too?" to make it clear it doesn't happen with any function having a function try block. But yes, in general, it's constructors and destructors with function try blocks that have this 'automatic rethrow' behavior. – usta Feb 23 '11 at 06:38