Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling multiple exceptions

I have written a class which loads configuration objects of my application and keeps track of them so that I can easily write out changes or reload the whole configuration at once with a single method call. However, each configuration object might potentially throw an exception when doing IO, yet I do not want those errors to cancel the overall process in order to give the other objects still a chance to reload/write. Therefore I collect all exceptions which are thrown while iterating over the objects and store them in a super-exception, which is thrown after the loop, since each exception must still be handled and someone has to be notified of what exactly went wrong. However, that approach looks a bit odd to me. Someone out there with a cleaner solution?

Here is some code of the mentioned class:

public synchronized void store() throws MultipleCauseException
    {
    MultipleCauseException me = new MultipleCauseException("unable to store some resources");
    for(Resource resource : this.resources.values())
        {
        try
            {
            resource.store();
            }
        catch(StoreException e)
            {
            me.addCause(e);
            }
        }
    if(me.hasCauses())
        throw me;
    }
like image 309
the-banana-king Avatar asked Mar 15 '10 01:03

the-banana-king


1 Answers

If you want to keep the results of the operations, which it seems you do as you purposely carry on, then throwing an exception is the wrong thing to do. Generally you should aim not to disturb anything if you throw an exception.

What I suggest is passing the exceptions, or data derived from them, to an error handling callback as you go along.

public interface StoreExceptionHandler {
    void handle(StoreException exc);
}

public synchronized void store(StoreExceptionHandler excHandler) {
    for (Resource resource : this.resources.values()) {
        try {
            resource.store();
        } catch (StoreException exc) {
            excHandler.handle(exc);
        }
    }
    /* ... return normally ... */
]
like image 91
Tom Hawtin - tackline Avatar answered Nov 15 '22 05:11

Tom Hawtin - tackline