Sometimes you need to write a constructor which can fail. For instance, say I want to instantiate an object with a file path, something like
obj = new Object("/home/user/foo_file")
As long as the path points to an appropriate file everything's fine. But if the string is not a valid path things should break. But how?
- throw an exception
- return null object (if your programming language allows constructors to return values)
- return a valid object but with a flag indicating that its path wasn't set properly (ugh)
I assume that the "best practices" of various programming languages would implement this differently. For instance I think ObjC prefers (2). But (2) would be impossible to implement in C++ where constructors must have void as a return type. In that case I take it that (1) is used.
In your programming language of choice can you show how you'd handle this problem and explain why?