Possible Duplicate:
How to handle failure in constructor in C++?
Is there any pattern in C++ so i could terminate object creation in constructor if something fails? And so client that invoke constructor got information about failed obj creation?
Yes, you can: throw an exception. This is pretty much the only sensible way. By choosing the appropriate exception class (either standard or your own) and supplying a good error message etc you'll be able to tell the caller what's gone wrong.
The FAQ has more details.
You need to throw an exception. That is the best way to handle failing object creation.
Constructor Failures should be an Interesting read from Herb Sutter's GOTW.
Another way of doing this is that if a constructor encounters an error, set a status bit and let the user call IsOK()
to see if construction actually worked.
But this is considered Obsolete.
Herb Says:
I have found the "if a constructor encounters an error, set a status bit and let the user call IsOK() to see if construction actually worked" method to be outdated, dangerous, tedious, and in no way better than throwing an exception.
Throwing an exception is the usual way to handle that, however, i discourage you from the pattern of throwing exceptions in constructors.
We cannot ensure that a constructor will not throw an exception but it seems to me an anti-pattern to rely on exceptions thrown by constructors. There is a subtle difference :)
I usually prefer to deal with constructors that should not fail, and move the sensible logic that can fail in an Initialize method that can return a value or throw an exception.
It is more clean and avoid you bad headache when the code gets more complicated!
This is an example of why I blieve so: http://www.cs.technion.ac.il/~imaman/programs/throwingctor.html
Another interesting post is C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With