How to write constructors which might fail to properly instantiate an object
- by whitman
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? You could:
1. throw an exception
2. return null object (if your programming language allows constructors to return values)
3. return a valid object but with a flag indicating that its path wasn't set properly (ugh)
4. others?
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?