2

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

Community
  • 1
  • 1
Hilikus
  • 9,954
  • 14
  • 65
  • 118
  • You might consider removing `listener` from `listeners` when this happens, though whether that is a good idea will depend on the application. – PJTraill Jun 10 '15 at 20:47
  • @PJTraill That's a good point. In some cases it might be the right thing to do – Hilikus Jun 11 '15 at 14:02

1 Answers1

1

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.

PJTraill
  • 1,353
  • 12
  • 30
Greg Hilston
  • 2,397
  • 2
  • 24
  • 35