How to write constructors which might fail to properly instantiate an object
        Posted  
        
            by 
                whitman
            
        on Programmers
        
        See other posts from Programmers
        
            or by whitman
        
        
        
        Published on 2011-03-20T19:24:23Z
        Indexed on 
            2011/03/20
            19:28 UTC
        
        
        Read the original article
        Hit count: 381
        
programming
|initialization
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?
© Programmers or respective owner