What Types Of Errors Are Caught By Try-catch Statements In Javascript?
Solution 1:
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.
Post a Comment for "What Types Of Errors Are Caught By Try-catch Statements In Javascript?"