HTML5 Study Notes (26): JavaScript error handling

Source: Internet
Author: User

Error-related debugging and processing is a particularly important skill in development.

Try-catch

Let's look at the following scenario:

1 // Nonefunc This method does not exist 2 Window.nonefunc (); 3 // JS Error after the termination of the operation of this line of code will not be executed to 4 console.log ("Hello");

To avoid situations where subsequent code cannot be executed, you can use the Try-catch command to enclose code that might throw the error.

1 Try {2     //Nonefunc This method does not exist3 Window.nonefunc ();4}Catch(Error) {5     //once the error is reached, it will be executed here .6Console.log (Error.message);//Window.nonefunc is not a function7 }8 //execution without interruption, this code will be executed9Console.log ("Hello");

It is important to note that the Error object has multiple properties, but the message property is a property supported by all browsers.

Finally

In a try-catch statement, the finally statement is an optional statement that, regardless of whether the code contained in the Try-catch contains an error, is bound to execute the code contained in the finally statement, as follows:

1 Try {2 window.test ();3}Catch(Error) {4 Console.log (error.message);5}finally {6Console.log ("Finally Code");7 }8 9 //Window.test is not a functionTen //finally code

Let's look at the following code:

1 functiontest1 () {2     Try {3         return0;4}Catch(Error) {5         return1;6}finally {7         return2;8     }9 }Ten  OneConsole.log (Test1 ());//2 A  - functiontest2 () { -     Try { the         return0; -}Catch(Error) { -         return1; -     } + } -  +Console.log (Test2 ());//0 A  at functiontest3 () { -     Try { -         //The test method does not exist - test (); -         return0; -}Catch(Error) { in         return1; -}finally { to         return2; +     } - } the  *Console.log (Test3 ());//2 $ Panax Notoginseng functiontest4 () { -     Try { the         //The test method does not exist + test (); A         return0; the}Catch(Error) { +         return1; -     } $ } $  -Console.log (Test4 ());//1

From the above example, the return statement contained in the Try-catch does not perform a return, only the return statement in the finally is executed, and the following example is shown:

1 functionTest () {2     Try {3         return0;4}Catch(Error) {5         return1;6}finally {7Console.log ("Finally");8     }9 }Ten  OneConsole.log (Test ());//0

If finally does not contain a return statement, then after executing the statement in Finally, after returning the value in the Try-catch statement , we look at the following example:

1 functiontest1 () {2     vari = 0;3     Try {4         return++i;5}Catch(Error) {6         return-1;7}finally {8         returni;9     }Ten } One  AConsole.log (Test1 ());//1 -  - functiontest2 () { the     vari = 0; -     Try { -         returni++; -}Catch(Error) { +         return-1; -}finally { +         returni; A     } at } -  -Console.log (Test2 ());//1

We find that although the return statement in Try-catch is not executed, the return statement in Try-catch is still executed, which can be understood as if there is a return keyword in finally. The return keyword in Try-catch is removed.

There is another situation, as follows:

1 functiontest1 () {2     vari = 0;3     Try {4         return0;5}Catch(Error) {6         return1;7}finally {8         if(I! = 0) {9             return2;Ten         } One     } A } -  -Console.log (Test1 ());//0 the  - functiontest2 () { -     vari = 0; -     Try { +         return0; -}Catch(Error) { +         return1; A}finally { at         if(i = = 0) { -             return2; -         } -     } - } -  inConsole.log (Test2 ());//2

We also found that the return statement in Try-catch is returned if the return statement in finally is not executed due to a condition such as a conditional judgment.

Error handling

In JavaScript, there are 7 types of built-in errors:

    • Error: The base class for the other 6 error types is also provided to the developer to define the new error types themselves.
    • Evalerror: An error occurred while performing the eval () method.
    • Rangeerror: The value out of range is an error, such as: New Array (-20) or new Array (Number.MAX_VALUE).
    • Referenceerror: An error occurred when the object was not found.
    • SyntaxError: Execute eval () method syntax error times wrong.
    • TypeError: Error when the type is incorrect, such as: New 10 or "name" in true.
    • Urierror: An error occurred while calling encodeURI and decodeURI.

For the browser, as long as the code contained in the Try-catch throws an error, the browser thinks that the error has been handled and we need to handle the error ourselves.

Throw error

Throw an error using the Throw keyword, for the type of error thrown is not specified, can be any type, and the browser throws the user error handling is also consistent with the built-in error, if there is no try-catch to include, the browser will pause the execution of JS.

We can simply throw an error type or custom type:

1 Throw {msg: "My Error"}; 2 Throw New Error ("our error");

We can inherit the error type and implement our own types of errors:

1 functionmyerror (msg, code) {2      This. Message =msg;3      This. Code =Code;4 }5 6Myerror.prototype =NewError ();7 8 Try {9     Throw NewMyerror ("My Error", 1001);Ten}Catch(Error) { OneConsole.log (Error.message + "," + Error.code);//my error, 1001 A}

Of course, it is recommended that the error object in the catch be type-filtered using the instanceof keyword and then a targeted processing error.

Error Event

The error event supports only DOM0-level listening methods, i.e. it cannot be registered and removed through the AddEventListener and RemoveEventListener methods, and the method does not create the corresponding event object, but transmits the error message directly.

You can understand that the error event is the Try-catch statement for the entire page, as follows:

1Window.onerror =function(message, URL, line) {2Console.log ("message:" + message + ", url:" + URL + ", line:" +Line );3     //returns True if the browser does not print error messages to the console console and returns False if the browser prints an error message4     return true;5 };6 7 test ();8 9 //Anyway, the code after the error is no longer executed.TenConsole.log ("Run this code!");

This event can be used to collect errors that are thrown by statements in the browser that are not surrounded by Try-catch when the app is developed, but in fact in the program that is published to the user, there should be no such error, because once the error event is thrown it means that the JS code execution is stopped.

HTML5 Study Notes (26): JavaScript error handling

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.