Object can throw exception on construction, but I don't want it to stop everything I have a factory that loads configuration from an xml file, and uses the configuration to be able to create objects of an appropriate type with appropriate settings. My application does a number of different tasks, and I don't want a broken or missing xml file to interfere with the other tasks the application does.

The factory is a Guice-provided dependency, however, if I make the constructor throw an exception, then I will just get a ProvisionException, which could cause unpredictable results or crash the application, neither of which are acceptable.

Currently, I have the factory swallow the exception on creation, and then throw it when the make method is called. Alternatively, I have a makeUnchecked method, if you call the ready() method first. Are there any problems with this approach, or is there potentially a better way to do it?

SSCCE:

public class FooFactory {
    private Exception ex = null;

    @Inject
    public FooFactory(@FooSettings String filename) {
        loadSettings(filename);
    }

    public void loadSettings(String filename) {
        try {
            // stuff
            this.ex = null;
        } catch(Exception e) {
            this.ex = e;
        }
    }

    public Foo make(InputObj input) throws Exception {
        if(ex != null) throw ex;
        makeUnchecked(input);
    }

    public Foo makeUnchecked(InputObj input) {
        if (ex != null) throw new IllegalStateException(ex);
        // factory stuff
    }

    public boolean ready() {
        return ex == null;
    }
}
My application does a number of different tasks, and I don't want a broken or missing xml file to interfere with the other tasks the application does.


If you don't need the XML file configuration, why do you have it? How can you continue without it?

How you answer this conceptual question has a lot to do with how you implement the code logic using exceptions.