Reputation: 2014
If I write
try { null = foobar } catch(e) { alert( e ) };
nothing is alerted, but a ReferenceError
is logged in the console. However,
try { barfoo = foobar } catch(e) { alert( e ) };
shows an alert with a ReferenceError
.
So the question is: what types of errors in what context get caught by try-catch statements?
Upvotes: 4
Views: 146
Reputation: 72839
So, your first line of code is invalid JavaScript syntax. That's why you're getting a:
ReferenceError: Invalid left-hand side in assignment
(You can't assign vars to null
)
Your second line is valid syntax, but throws a:
ReferenceError: foobar is not defined
.
Now, the reason the second line does get caught, but the first one doesn't, is because the JavaScript interpreter is throwing the first error when interpreting the code, compared to when it's actually executing it, in the second example.
A more simple explanation, courtesy of @Matt:
It's simply invalid JavaScript syntax vs runtime errors. The latter get caught, the former doesn't.
You can sort of thinking it as the JavaScript interpreter looking at all the code before it executes it and thinking does that all parse correctly? If it doesn't, it throws an uncatchable
Error
(be it aSyntaxError
orReferenceError
). Otherwise, the code beings to execute, and at one point you enter the try/catch block during execution and any runtime errors thrown whilst in there are caught.
Upvotes: 4