views:

50

answers:

1

//sample.h

int calci(int &value)
{
   if(value < 20)
    throw value;
   else
     return value;
}

class XYZ
{
   int m_x;
   public: XYZ(int &x)try:m_x(x-calci(x))
          {
          }catch (int &a)
          {}

};
class ABC
{
   int m_a;
   public: ABC():m_a(0)
   {
   }
    void foo()
    {
        XYZ xyz(10);


    }
};




int main()
{
   ABC abc;
   abc.foo();
}

//if i replace foo() with following code then it works well

void foo()
{
  try{
    XYZ xyz(10);
  }catch(...){}
}
+5  A: 

From: http://gotw.ca/gotw/066.htm

What's less obvious, but clearly stated in the standard, is that if the catch block does not throw (either rethrow the original exception, or throw something new), and control reaches the end of the catch block of a constructor or destructor, then the original exception is automatically rethrown.

From standard 15.3/16

The exception being handled is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. Otherwise, a function returns when control reaches the end of a handler for the function-try-block (6.6.3). Flowing off the end of a function-try-block is equivalent to a return with no value; this results in undefined behavior in a value-returning function (6.6.3).

Andreas Brinck