Vijay Vijay - 1 month ago 12
C++ Question

exception handling a constructor

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?

Answer

See this GOTW Constructor Failures question which addresses your query somewhat and goes on to say it is a waste of time.