Ex in [Javascript]catch (ex) statements

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.