Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle failure in constructor in C++?

Tags:

c++

I want to open a file in a class constructor. It is possible that the opening could fail, then the object construction could not be completed. How to handle this failure? Throw exception out? If this is possible, how to handle it in a non-throw constructor?

like image 799
Thomson Avatar asked Feb 14 '11 07:02

Thomson


People also ask

What happens when constructor fails?

If an exception is thrown in a constructor, the object was never fully constructed. This means that its destructor will never be called. Furthermore, there is no way to access an object in an error state. The exception will immediately unwind the local variable.

Can constructor fail?

A constructor may well open a file (not necessarily a bad idea) and may throw if the file-open fails, or if the input file does not contain compatible data. It is reasonable behaviour for a constructor to throw an exception, however you will then be limited as to its use.

Is it OK to throw exception 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.


1 Answers

If an object construction fails, throw an exception.

The alternative is awful. You would have to create a flag if the construction succeeded, and check it in every method.

like image 200
BЈовић Avatar answered Oct 08 '22 21:10

BЈовић