What\'s the best technique for exiting from a constructor on an error condition in C++? In particular, this is an error opening a file.
Thanks for the responses. I\'
There is only 1 good way to exit from a constructor that is in error, that is to raise an exception.
Is it really an error? are you trying to add too much to the constructor?
Often people will try and roll in some initial interaction into the constructor, like adding the filename to a file constructor. Do you expect it to open that file right away or are you just setting some state, is it different to file.open(filename), is it ok if it fails?
If you object after the error can not perform its actions - you have to throw. If it can - log you error and change the construction logic.