Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 679
Vijay Avatar asked Apr 21 '11 10:04

Vijay


People also ask

Can we handle exceptions in constructor?

The short answer to the question “can a constructor throw an exception in Java” is yes! Of course, properly implementing exceptions in your constructors is essential to getting the best results and optimizing your code.

Can I throw exception in constructor?

Yes, constructors are allowed to throw an exception in Java. A Constructor is a special type of a method that is used to initialize the object and it is used to create an object of a class using the new keyword, where an object is also known as an Instance of a class.

Can you throw exception in constructor C#?

Throwing exceptions in constructors in C# is fine, but a constructor should always create a valid object.


2 Answers

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

like image 114
dubnde Avatar answered Sep 29 '22 10:09

dubnde


Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception. If you don't have the option of using exceptions, the "least bad" work-around is to put the object into a "zombie" state by setting an internal status bit so the object acts sort of like it's dead even though it is technically still alive.

You would catch the exception in the calling code, not within the constructor.

See How can I handle a constructor that fails? for further details (actually, I'd suggest reading the whole page about exception handling, truly enlightening).

like image 29
helpermethod Avatar answered Sep 26 '22 10:09

helpermethod