How to understand and use try... catch... finally in javascript

Source: Internet
Author: User
Tags error handling exception handling try catch


Try...catch...finally's understanding

Before, I always liked to use Console.log (do some thing) to perform output type and value, want to see the pop-up information immediately, It will be directly in the browser alert (), which is the basic knowledge. The

is a little bit more complex, using a judgment statement, if else to make conditional judgments, saying if conditions are otherwise, such judgments are very familiar to code Lennon, which writes program code.

If you think this is also simple, you might use a mixed if else conditional judgment statement plus a try catch to handle the statement, although you can handle any object with a try catch and throw a bad statement through throw. Then catch throws the object or the object's error, today we only say Try...catch, the following example throws an array, a time, a prototype function, a numeric type, and so on.


function trycatch () {
     var array = [234],
         newdate = new Date (),
         fun = function () {},
         is = 12.22,
         call;
     try {
         throw array + '\ n' + newdate.toLocaleString () + '\ n' + fun.prototype.constructor +
         '\ n' + (typeof is == 'number') + '\ n' + call; // Be careful that there is an 'e' after the local
     }
     catch (e) {
         console.log (e);
     }
     finally {
         console.log ('err finally');
     }
}
trycatch ()
// Output:
// 234
// 10/12/2015 10:07:03 PM
// function () {}
// true
// undefined



To be more precise, put a statement that might produce an error inside the try. When the try statement starts executing and throws an error, the catch executes the internal statement and the error message in the corresponding try. When a finally statement is executed, the finally statement is executed only after the try and catch statements have been executed, regardless of whether a try throws an exception or catch capture executes the finally statement.


function Trycatch () {
try{
throw new Error (' Koringz ');
catch (E) {
console.log (e.message);
}
finally{
console.log (' err finally ');
}
Trycatch ()//
output:
//Koringz
//Err finally



With a try throw out a wrong statement, we see the catch caught in a wrong message//Koringz, but the same finally also output/err finally. Although we know how to handle a try catch workflow, but do not understand the code handlers of finally blocks, as we have always thought about finally statements, the finally output is not constrained and constrained by try and catch. Here are some of the finally output demo codes:


function Trycatch () {
try{
throw new Error (' Koringz ');
}
finally{
console.log (' err finally ');
Return Console.log (' new finally ')
}
Trycatch ()
//Err finally
/new finally



As shown above, the try throws a wrong statement, finally the result of the output is://Err finally//new finally.


function Trycatch () {
try{
throw new Error (' Koringz ');
catch (E) {
console.log (' err finally ');
Return Console.log (' new finally ')
}
Trycatch ()
//Err finally
/new finally




As shown above, the try throws an error statement, catch catches the error output, and finally. Err finally//new finally.

When I modify a try statement:


function Trycatch () {
try{
//
}
catch (e) {
console.log (' err finally ');return Console.log (' new Finally '
}}
Trycatch ()
//Empty (Viod)
//Empty (Viod)



As a result, the output is empty. Empty (Viod). Because the try did not throw the error, the catch did not catch the exception, so the output is empty.

So let's take a look at the following case, which may give you a better idea of the exception handling of the try Catch statement, as shown in the following example.


try{
try{
throw new Error (' Open ');
catch (E) {
console.info (e.message);
Throw e
}
finally{
console.log (' finally ');
catch (e) {
console.log (' op ', e.message);
}
Open
//finally
//OP Open


When we nest a try catch in a block of code blocks that might throw an error, throw a statement throw new error (' Open ') through a nested code block try, and immediately after the nested try passes the error to the nested catch handle. After finally running through the nested finally run, we see the last Result//Op open, in fact, nested catch-caught error messages are thrown at the outermost catch capture. OP Open

In other words: Any given exception is only caught once by the enclosing catch block closest to it.

Of course, any new exception thrown in the "inside" block (because the code in the catch block can also throw an exception) will be captured by the "outside" block.



use of Try Catch finally in JavaScript

try...catch...finally statement

Implement error handling for JScript.
try {
Trystatements}
catch (Exception) {
Catchstatements}
finally {
Finallystatements}
=============
Parameters
Trystatement
Required option. The statement that the error may occur.
exception
Required option. Any variable name. The initialization value of the exception is the value of the error thrown out.
Catchstatement
Options available. A statement that handles errors that occur in the associated trystatement.
Finallystatements
Options available. A statement that executes unconditionally after all other processes occur.
Description
The try...catch...finally statement provides a way to handle some or all of the errors that can occur in a given block of code while still keeping the code running. If there is an error that the programmer has not handled, JScript simply gives the user its normal error message, as if there were no error handling.

The trystatements parameter contains code that may have an error, and Catchstatement contains code to handle any errors that occurred. If an error occurs in the trystatements, the program control is passed to catchstatements for processing. The initialization value of the exception is the value of the error that occurred in trystatements. If the error does not occur, the catchstatements is not executed.

If the error is not handled in the catchstatements associated with the trystatements in which the error occurred, the throw statement is used to propagate, or to throw back the error, to a more advanced error handler.

The statements in finallystatements can be executed unconditionally after the statements in Trystatements are executed and after all error handling of catchstatements occurs.

Note that even if you return a statement in a try or catch block, or if you throw an error back in the catch block, the finallystatements encoding is still performed. It is generally ensured that the finallystatments is running unless an unhandled error exists. (for example, a run-time error occurs in a catch block.) )。

Example



The following example illustrates how JScript exception handling is done.


try {
        print ("Outer try running ..");
        try {
            print ("Nested try running ...");
            throw "an error";
        }
        catch (e) {
            print ("Nested catch caught" + e);
            throw e + "re-thrown";
        }
        finally {
            print ("Nested finally is running ...");
        }
    }
    catch (e) {
        print ("Outer catch caught" + e);
    }
    finally {
        print ("Outer finally running");
    }
    // Windows Script Host makes this modification to get WScript.Echo (s)
    function print (s) {
          document.write (s);
    } 



   will draw the following results:   
    
   outer    try     running ...   &NBSP
   nested    try    running...   
    nested    catch    caught    an    error  &NBSP
   nested    finally    is    running...  &NBSP
   outer    catch    caught    an     error    re-thrown   
   outer    finally     Running


is an example of JavaScript exception handling as follows.


var array = null;
try {
document.write (array[0]);
} catch (Err) {
Document.writeln ("Error name: + Err.name +");
Document.writeln ("Error message:" + err.message);
}
finally{
Alert ("Object is null");
}



Program execution Process

1. array[0] When an array is not created and an array is an empty object, calling Array[0 in a program produces an exception with object is null
2. The catch (ERR) statement captures the exception by err.name the error type, Err.message prints the error details.
3. Finally, the Java-like finally, regardless of whether there is no exception will be executed.


Summary of the Error.name six values corresponding to the information:
1. The use of Evalerror:eval () is inconsistent with the definition
2. Rangeerror: Value out of bounds
3. Referenceerror: Illegal or unrecognized reference value
4. SyntaxError: Syntax resolution error occurred
5. TypeError: Error of operand type
6. Improper use of urierror:uri processing function


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.