3

In below code snippet while throwing exception from Base class's constructor programme got aborted. I believe derive class has already handled exception properly but still programme got terminted and gracefull exit from programme didn't happen. Could you let me know what wrong with this approach as if exception is handled in main function by imposing try catch block on derive class object p then rogramme is not terminated.

#include <iostream>
#include <memory>
using namespace std;
class A
{
  int *memory;
  public:
  A()
  {
   cout<<"calling constructor class A\n";
   memory= new int [100000000000000];

  }
  void show()
  {
  cout<<"show A\n";
  }
  ~A()
  {
    cout<<"calling destructor class A\n";
  }
};

class B : public A
{
  public:
 B()

  try :A() {
  cout<<"calling B's constructor\n";
  }
  catch(...)
  {
  cout << "exception occurred\n";
  }
  ~B()
  {
    cout<<"calling B's destructor\n";
  }


};

int main()
{
B obj;
obj.show();
return 1;
}
user2997518
  • 812
  • 6
  • 17
  • 2
    Exceptions caught in a function-try block of a constructor are automatically rethrown unless the handler throws something. (You can't use the object anyway since it hasn't been fully constructed.) Here's a [decent article about it](http://gotw.ca/gotw/066.htm). – molbdnilo Jul 06 '15 at 09:14
  • +1 for sharing this information. But still we can avoid the programme termination by introducing the one more try catch block in main function by throwing from catch block again which doesn't seems to be good design. I have seen in many places in my project that inside catch block we are throwing again . – user2997518 Jul 06 '15 at 11:20

0 Answers0