Alex Rivera | Logout

exception handling a constructor

Asked 2011-04-21T10:45:15.170
19

This was an interview question of me.

Surprisingly i never thought of this kinda question to myself.

can we have exception handling inside a constructor c++?

in tense and not thinking much i said "yes we could probably do it in a constructor.lets say we are allocating some memory using new operator to a pointer member and it throws a bad alloc exception,in this way there is a possibility of exceptions being raised"

Then later i thought that constructors can never return a value.So how can an exception inside a constructor caught.now i am asking this to myself!

can anybody pls help me to come out of this confusion?

Edit
Report

1 Answer

-2

C++ has try-catch clauses similar to those of other languages. A tutorial can be found online: http://www.cplusplus.com/doc/tutorial/exceptions/

EDIT: example turned into fully working code

#include <iostream>
using namespace std;

class A
{
public:
  void f(){
    throw 10;
  }

  A(){
    try{
      f();
    }
    catch(int e){
      cout << "Exception caught\n";
    }
  }
};

int main (int argc, const char * argv[])
{

  A a;
  return 0;
}

This produces output:

Exception caught
answered 2011-04-21T10:47:12.573

Your Answer