1
#include <iostream>

using namespace std;

class B
{
  public:
        ~B()
        {  throw 42;  }
};

int main()
{
  try
  {
    B obj;
    throw 32;
  }
  catch( int i )
  {  cout<<i<<endl;  }
}

When the above code is executed program terminates abruptly.

  1. Why does it end abruptly?
  2. How to handle this kinda exception?

Note : This was asked in online test.

Dinesh Gowda
  • 1,044
  • 3
  • 13
  • 29
  • When `throw 32;` is executed the scope (the surrounding curly braces) is left. Hence, `B obj;` is destructed and `throw 42;`. Phew... throwing while throwing. I'm not sure how this is exactly defined but _abrupt termination_ seems possible to me. – Scheff's Cat Mar 14 '19 at 06:30
  • 1
    @Scheff - It's defined by a call to `std::terminate` - so indeed very possible :) – StoryTeller - Unslander Monica Mar 14 '19 at 06:31
  • I found another Q/A which could be a duplicate: [SO: Throwing an exception while throwing an exception](https://stackoverflow.com/q/16804065/7478597). – Scheff's Cat Mar 14 '19 at 06:32
  • An answer that contains relevant text from the C++ standard: https://stackoverflow.com/a/739424/434551. – R Sahu Mar 14 '19 at 06:44

0 Answers0