Are thrown errors in a try block considered to be handled even if there's no catch block?
Andy Earnshaw
andyearnshaw at gmail.com
Fri Jun 23 09:20:35 UTC 2017
A long trip down a rabbit hole has brought me here. Long story short(ish),
I was attempting to replicate how `EventTarget.prototype.dispatchEvent()`
works in plain JavaScript code. A naive implementation (like Node's
EventEmitter) would simply loop over any bound handlers and call them in
turn. However, this isn't very robust because one bound handler can
prevent the rest from executing if it throws.
DOM's dispatchEvent() doesn't have this problem. Consider the following
code:
```
target = document.createElement('div');
target.addEventListener('foo', () => { throw 1; });
target.addEventListener('foo', () => { throw 2; });
target.addEventListener('foo', () => { throw 3; });
target.dispatchEvent(new CustomEvent('foo'));
```
If executed in a browser, I see:
> Uncaught 1
> Uncaught 2
> Uncaught 3
Even though each one throws, they all still execute. In our naive
implementation, if you wrap each callback with a try/catch, errors thrown
become handled, so the callback provider might not be aware of errors or it
may be difficult to debug them without a stack trace. Global error handlers
aren't triggered either. If you swap out the catch block for a finally
block (with either `continue` or some kind of recursive iteration), the
errors aren't technically handled, but only that last one is considered
"uncaught".
I've observed this behaviour in current versions of Chrome, Firefox and
Safari. Does that mean the spec defines finally blocks to behave this way,
or is it just an implementation-dependant behaviour they've all converged
on?
PS I realise that dispatchEvent's behaviour stems from it creating a new
job for each handler function. Interestingly, you can achieve something
similar in browsers by appending a new script element per handler function
to call it. Not great for performance or achieving this transparently, but
it works as a sort of proof-of-concept.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170623/d05a9b88/attachment.html>
More information about the es-discuss
mailing list