Should I catch Exception, Throwable or other in EventDispatcher/Observable

352 views Asked by At

It is usually not recommended to catch generic exceptions like Exception or Throwable since you take the burden of dealing with problems that you don't know how to deal with (like out of memory error). However, in an "robust" observer pattern implementation (one in which the error of a listener should not stop other listeners from being notified), an event publisher might be observed by anyone, meaning that the event listener might throw exceptions that the event publisher cannot possibly know (and that's the whole point of decoupling listener and publisher).

In this case, does it make sense to catch Throwable so that no matter what error happens in the event processing, other listener will still be notified? Or is it still a bad idea to catch such a generic class?

Something like this

for (EventHandler listener : listeners) {
     try {
        listener.sendEvent(event);
     } catch (Throwable exc) {
        log.warn("Listener " + listener + " failed to process event");
        //maybe remove faulty listener...
     }

  }

Another, heavier alternative I can see to isolate failure of listeners is to use a thread pool so that if a listener throws an exception, only the thread of the pool will be lost but notification of other listeners will still happen

1

There are 1 answers

0
Greg Hilston On BEST ANSWER

I'd recommend catching Throwable as I find your argument conclusive that “an event publisher might be observed by anyone, meaning that the event listener might throw exceptions that the event publisher cannot possibly know”.

The alternatives are not catching anything, which would be a nightmare, or your suggestion of a thread pool, which I believe is unnecessary when you catch Throwable.