The Try/catch statement is the exception-handling mechanism provided by the JavaScript statement, which, once the statement inside the try statement block throws an exception, captures the exception information of the error type in the Catch statement block. We know there is no block scope in JavaScript, but this common sense has the opposite effect in the catch statement block. Look at the following code:
(function() { try{ thrownew error ("Error" ); } Catch (ex) { console.log (ex.message); } finally { Console.log ("final"); } Console.log (ex);}) ();
The last line of the above code is console output (Console.log (ex);) An exception prompt will be thrown without the identifier of the ex. This phenomenon indicates that in a catch statement block, the scope of the ex is confined only to the inside of the statement block, and the external cannot resolve to the ex identifier.
Make a small adjustment to the above code, and again declare ex as a variable inside the catch.
(function() { try{ thrownew error ("error"); } catch(ex) { console.log (ex.message); var ex = "ex string"; } finally { Console.log ("final"); } Console.log (ex);}) ();
This time the last line console output (Console.log (ex);) Do not throw the exception, but he output is the undefined value, the catch statement block in the assignment statement does not affect the declaration of the ex variable, but to the catch captured ex is assigned value. This is a strange phenomenon, and the precedence of variable name resolution is overwritten by the identifier of the catch exception.
Ex in [Javascript]catch (ex) statements