JavaScript try...catch statements

Source: Internet
Author: User
Tags finally block



The try ... catch statement places the error-causing code in a try block, corresponding to a response, and then an exception is thrown.


Grammar
try {
   try_statements
}
[catch (exception_var_1 if condition_1) { // non-standard
   catch_statements_1
}]
...
[catch (exception_var_2) {
   catch_statements_2
}]
[finally {
   finally_statements
}]




try_statementsthe statement that needs to be executed.catch_statements_1,catch_statements_2The statement executed if there is an exception thrown in the try block.exception_var_1,exception_var_2a variable used to hold the thrown object is based on the associated catch clause.condition_1a conditional expression.finally_statementsAblock of statements that executes after a try statement block. These statements are executed regardless of whether an exception is thrown or captured.Describe


A try statement consists of a try block consisting of one or more statements, and at least one of the catch clauses or one of the finally clauses, or two concurrently, following the three forms of the try Declaration:


    1. try...catch
      try...finally
      try...catch...finally



The catch clause contains a specific statement that throws an exception in a try block. That is, you want to try this try statement whether successful, if unsuccessful you will go to control through the catch block. If there is any one statement in the try block (or a function called from a try block), the control immediately shifts to the catch clause. If no exception is thrown in the try block, the catch clause is skipped.



The finally clause executes after the try block and catch block but before the next try declaration. Regardless of whether there is an exception thrown or caught it is always executed.



You can nest one or more try statements. If the internal try statement does not have a catch clause, it enters the catch clause of the try statement that encloses it.



You can also use a try statement to handle JavaScript exceptions. Refer to JavaScript Guide for more information on JavaScript exceptions.


Unconditional catch clause


When a single unconditional catch clause is used, a catch block execution statement is entered when an exception is thrown. For example, when the following code has an exception, control will turn to the catch clause.


try...catch
try...finally
try...catch...finally




Conditional catch clause





Non-standard
This feature is non-standard, please try not to use it in a production environment!






You can also use one or more conditional catch clauses to handle specific exceptions. In this case, when the exception is thrown, it goes into the appropriate catch clause. In the following code, the code of the try block may throw three exceptions:TypeError,RangeError, andEvalError. When an exception is thrown, the control enters its corresponding catch statement. If the exception is not specific, then the control is transferred to the non-conditional catch clause.



When a non-conditional catch clause and one or more conditional statements are used, the non-conditional catch clause must be placed last. Otherwise, all exceptions will be blocked by non-conditional statements before they reach the conditional statement.



Reminder: This feature does not conform to the ECMAScript specification.


try {
    myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
    // statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
    // statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
    // statements to handle EvalError exceptions
} catch (e) {
    // statements to handle any unspecified exceptions
    logMyErrors(e); // pass exception object to error handler
}
 





The following is a simple javascript that conforms to the ECMAScript specification to write the same conditional catch clause (which is obviously more verbose, but can be run anywhere):


try {
    myroutine(); // may throw three types of exceptions
} catch (e) {
    if (e instanceof TypeError) {
        // statements to handle TypeError exceptions
    } else if (e instanceof RangeError) {
        // statements to handle RangeError exceptions
    } else if (e instanceof EvalError) {
        // statements to handle EvalError exceptions
    } else {
       // statements to handle any unspecified exceptions
       logMyErrors(e); // pass exception object to error handler
    }
}




Exception identifier


When an exception is thrown in a try block, exception_var (e.g.ethe incatch (e)) is used to hold the value specified by the thrown declaration. You can use this identifier to get information about the exception being thrown.



This identifier is internal to the catch child statement. In other words, when the identifier is created when the Catch child statement is entered, it is no longer available after the Catch child statement has finished executing.


Finally clause


The finally clause executes after a try block and a catch block but before a try declaration. Regardless of whether there is an exception thrown or caught it is always executed. If an exception is thrown, the finally clause will be executed, even if there is no catch clause to handle the exception.



You can use the FINALLY clause to make your script end more elegant, for example, you might need to release resources that your script has already used. The following example opens a file and executes the statement using the file (the server-side JavaScript allows you to access the file). If an exception is thrown when the file is opened, the finally clause closes the file before the script ends.


openMyFile()
try {
   // tie up a resource
   writeMyFile(theData);
}
finally {
   closeMyFile(); // always close the resource
}
 




Example Nesting try-blocks


First let's see what happens here:


try {
  try {
    throw new Error("oops");
  }
  finally {
    console.log("finally");
  }
}
catch (ex) {
  console.error("outer", ex.message);
}

// Output:
// "finally"
// "outer" "oops"





Now, if we've caught an exception by adding a catch statement block


try {
  try {
    throw new Error("oops");
  }
  catch (ex) {
    console.error("inner", ex.message);
  }
  finally {
    console.log("finally");
  }
}
catch (ex) {
  console.error("outer", ex.message);
}

// Output:
// "inner" "oops"
// "finally"





Now, let's throw the error again.


try {
  try {
    throw new Error("oops");
  }
  catch (ex) {
    console.error("inner", ex.message);
    throw ex;
  }
  finally {
    console.log("finally");
  }
}
catch (ex) {
  console.error("outer", ex.message);
}

// Output:
// "inner" "oops"
// "finally"
// "outer" "oops"





Any given exception will only be captured once by the enclosing catch block closest to it. Of course, any new exceptions thrown in the "inner" block (because the code in the catch block can also throw exceptions) will be captured by an "external" block.


Returning from the finally block


If a value is returned from the finally block, the value will be the return value of the entire try-catch-finally, regardless of whether there is a return statement in the try and catch. This includes exceptions thrown in the catch block.


try {
  try {
    throw new Error("oops");
  }
  catch (ex) {
    console.error("inner", ex.message);
    throw ex;
  }
  finally {
    console.log("finally");
    return;
  }
}
catch (ex) {
  console.error("outer", ex.message);
}

// Output:
// "inner" "oops"
// "finally"





Because the return statement in the finally block, the external "oops" exception is not thrown. The value returned from the Catch block also applies.


Specification
Specification Status Comment
ECMAScript 3rd Edition Standard Initial definition.
Implemented in JavaScript 1.4
ECMAScript 5.1 (ECMA-262)
Try Statement
Standard
ECMAScript 6 (ECMA-262)
Try Statement
Release candidate


Not part of a ECMA-262 standard:multiple catch clauses and conditional clauses (spidermonkey extension, JavaScript 1.5).


Browser compatibility




    • Desktop
    • Mobile
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic Support (Yes) (Yes) (Yes) (Yes) (Yes)
Conditional clauses
(non-standard)
Not implemented (Yes) Not implemented Not implemented Not implemented




See
      • Error
      • throw


JavaScript try...catch statements


Related Article

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.