JavaScript exception handling (try...catch...finally Window.onerror)

Source: Internet
Author: User
Tags try catch
Try Catch Finally statement description

Try Catch finally is the exception handling mechanism provided by the JavaScript language. The grammatical structure is as follows

1 try {
 2   //This code runs from top down, where any one of the statements throws an exception the code block ends running
 3 
 4}
 5 catch (E) {
 6   //If an exception is thrown in the try code block, The code in the catch code block is executed.
 7   //e is a local variable that points to the error object or other thrown object
 8}
 9 finally {   / The finally code block is always executed, regardless of whether the code in the try is thrown unexpectedly (even if there is a return statement in the try block of code).
the  }

Try...catch...finally ... Catch and finally are optional in syntax except try (both must have one), that is to say try...catch...finally ... There are three forms of grammar:

try{

Some code

}

catch (e) {

Somecode

}

finally{

Some code

}

try{

Some code

}

catch (e) {

Somecode

}

try{

Some code

}

finally{

Some code

}

If there is a catch, once the code in the try throws an exception, the code in the catch is executed first, and then the code in finally is executed. If there is no catch statement, the code in the try throws an exception, executes the statement in finally, and then throws the exception thrown in the try in an unusual way.

No matter how the execution of a try block is executed (exception, return, natural termination) The statement in finally is always executed, and it is because of finally this feature that it is usually finally used to perform some cleanup work. If the code in try is terminated in a return,continue,break manner, the JavaScript engine executes the return statement in the corresponding try after executing the statement in finally.


Throw Statement Description

    The throw statement has been implemented in javascript1.4. The syntax for try is simple, as follows
1 throw expression;

The expression can be of any type, meaning that throw "There is a error" or throw 1001 are correct. But usually we throw an error object or a subclass of the Error object. About the error we will introduce later, first look at a section of throw sample code.

1 function factorial (x) {
2     //If The input argument is invalid, throw an exception!
3     if (x < 0) throw new Error ("x must not to be negative");
4     //Otherwise, compute a value and return normally
5 for     (var f = 1; x > 1; F *= x, x--)/* empty * *;
6 return     F;
7}

Error Object

The Error object and its subclasses are implemented in javascript1.5. There are two types of error constructors

1     New error ()
2 
3     new error (message)

The error has two basic property name and message. The message is used to represent the details of the exception. and name refers to the constructor of the error object. In addition, the different JS engine for the error also provides a number of extensions, such as Mozilla provides filename (abnormal file name) and linenumber (abnormal occurrence of the line number) expansion, and IE provides number (error) support. However, the name and message are two basic attributes that can be supported in both Firefox and IE. JavaScript error There are several subclasses Evalerror, Rangeerror, Referenceerror, SyntaxError, TypeError , urierror, Their meaning is not here in detail, readers can find references in the reference documents I provide.


JavaScript's exception handling mechanism and Window.onerror handle

When the JavaScript code in the error, the JS engine will be based on the call stack of JS to find the corresponding catch, if not find the corresponding catch handler or catch handler itself and have error or throw new error, Finally, the processing of this error to the browser, the browser will use their own different ways (ie with yellow triangle pattern shown in the lower left corner, and Firefix will be displayed in the error console) to display error messages to visitors. In many scenarios, we feel that this kind of error is not friendly enough, and that the message is very covert, then we have the opportunity to customize the way this error message. The answer is yes, it is the Window.onerror attribute.

The JavaScript Window object has a special attribute onerror, and if you assign a function to the window's OnError property, there is a JavaScript error in the window. The function is invoked, which means that the function becomes the error handling handle of this window.

1//Display error Messages in a dialog box, but never more than 3
2 window.onerror = function (msg, URLs, line) {
3     if (onerror.num++ < Onerror.max) {
4         alert ("ERROR:" + msg + "\ n" + URL + ":" + line);
5 return         true;
6     }
7}
8 Onerror.max = 3;
9 Onerror.num = 0;

The onerror handle will have 3 parameters that are error message prompts, resulting in the error of JavaScript document ULR, and error occurrence line number.

The return value of the Onerroe handle is also important if the handle returns true, which means that the browser does not need to do extra processing on the error, which means that the browser does not have to display the error message again. If you return false, the browser prompts you for an error message.

1 window.onerror=function () {
 2 
 3 alert ("XX");
 4 
 5 return true;//If you comment out the statement, there will be an error in the browser, otherwise there is no.
 6 
 7}
 8 
 9 function ThrowError () { 
throw new Error ("CC"); 
13}

We can not avoid some JS exception in the process of developing HTML, usually we can not rely on the customer to open the browser error prompt box (such as the above) to provide clues for us to locate the bug, and using the Window.onerror handle we can tell the error message display, the customer as long as the error appears, provide the appropriate screenshots, this can be a good help to developers positioning, analysis of JavaScript-related errors. reference materials

Mozilla Javascript1.5 Core Reference

JavaScript Rhino (javascript:the definitive Guide)

"Turn" http://snap.oncoding.cn/javascript/base/article200907/216.html

need to remove disable script debugging (IE)

Display error messages in a dialog box, but never more than 3
Window.onerror = function (msg, URL, line) {
if (onerror.num++ < Onerror.max) {
Alert ("ERROR:" + msg + "\ n" + URL + ":" + line);
return true;
}
}
Onerror.max = 3;
Onerror.num = 0;

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.