JavaScript exception handling using summary _javascript tips

Source: Internet
Author: User
Tags exception handling finally block try catch
Exceptions in JavaScript can be used with a try ... Catch.. Finally statement to process, or you can manually throw an exception.
1. Use Try ... Catch.. Finally statement to handle exceptions
JS code in the execution of an exception, you will manually create an exception class object, the Exception class object will be submitted to the browser, this process is called "throw an exception." When a browser receives an object, it looks for code that can handle the exception and submits the current exception object to its processing, a process known as "catching an exception." Try.. Catch.. The basic syntax format for finally statements is:
Copy Code code as follows:

try{//code that might throw an exception
}catch (Error) {//If an exception occurs the code that executes, error is the exception class object that occurred
}finally{//Unconditional execution of code
}

In the above statement, the catch statement is immediately following the try statement, and finally the statement immediately follows the catch, which is the writing of a complete exception-handling statement. In fact, both catch and finally statements can be omitted, but they should be used in conjunction with at least one of them and a try statement.
A statement in a try block is not necessarily a statement to throw an exception, and any JavaScript statement can be handled with an exception-handling statement, but this is not necessary. When the code for a row in a try block throws an exception, the code underneath the line is not executed, and the code of the catch block is executed directly.
In a catch block, the error in parentheses behind the catch statement indicates an instance of the exception object that is caught, which contains the details of the exception, which can be appropriately handled according to that information. If there is a finally statement after the catch statement, the statement in the finally block continues to execute.
The statement in the finally block is the statement that is always executed, and the statements in the block usually do some final cleanup. If you encounter statements that transfer processes such as return statements, continue statements, or break statements before executing a finally block, then the code in the finally block is executed before executing the statements.
If in an exception-handling statement, contains only try ... A catch statement that has a finally statement that does not have a replenishment exception executes the statement in the try block directly after the statement of the finally block, and then throws the exception.
Cases:
Copy Code code as follows:

<script>
try{
var date=new date ();
Date.test ();//Call Date's undefined test method;
Document.wrire ("Try Block execution end <br>");
}catch (Error) {
With (document) {
Write ("Abnormal <br>" occurred);
Write ("Exception type:" +error.name+ "<br>");
Write ("Exception message:" +error.message);
}
}finally{
document.write ("Exception processing complete!") ");
}
</script>

Results:
An exception has occurred
Exception type: TypeError
Exception message: Object does not support this property or method exception handling complete!
2. Manually throwing Exceptions
In addition to the Run-time browser throwing an exception, developers can also throw exceptions themselves. The statement that is thrown by a manual exception is throw, and its basic syntax format is:
throw expression;

Try Catch Finally statement description

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

try {
 //This code runs from top down, and any one of the statements throws an exception and the code block ends up running
catch (E) {
 //If an exception is thrown in the try code block, the code in the catch code block is executed.
 //e is a local variable that points to an error object or other thrown object
}
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).
 }

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
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.

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

Error Object

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

New Error ()
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(异常出现的文件名称)和linenumber(异常出现的行号)的扩展,而IE提供了number(错误号)的支持。不过name和message是两个基本的属性,在firefox和ie中都能够支持。Javascript中Error还有几个子类 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 the error hint? 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.

Display error messages in a dialog box, but never more than 3
window.onerror = function (msg, URLs, line) {
 if (o nerror.num++ < Onerror.max) {
  alert ("ERROR:" + msg + "\ n" + URL + ":" + line);
  return true;
 }
Onerror.max = 3;
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.

Window.onerror=function () {

Alert ("XX");

return true; If you comment out the statement, there will be errors in the browser, otherwise there is no.

}

function ThrowError () {

throw new Error ("CC");

}

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.

Resources

Mozilla Javascript1.5 Core Reference

JavaScript Rhino (javascript:the definitive Guide)

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.