简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM