JavaScript advanced programming Reading Notes (20) js error handling

Source: Internet
Author: User

I. Error Classification

1. syntax error: it is also called a parsing error. It occurs during compilation in traditional languages and occurs in JavaScript during interpretation. These errors are directly caused by unexpected characters in the Code and cannot be directly compiled/interpreted. When a syntax error occurs, the Code cannot be executed. In JavaScript, only the code in the same thread is affected by syntax errors. Code in other threads and other externally referenced files can be executed if it does not depend on the code that contains the error.
2. runtime error: Also known as exception (exception, after the compilation/Interpreter ). At this point, the problem is not in the code syntax, but an operation that is attempted, in some cases, illegal. Exceptions only affect the threads that occur. Other JavaScript threads can continue normal execution.

Ii. Error Handling

JavaScript provides two methods to handle errors: The onerror event processing function in BOM and the try... catch Method in ECMAScript.
1. onerror event processing functions
It is the first mechanism to assist JavaScript in error handling. When an exception occurs on the page, the error event is triggered on the window object. For example:

Copy codeThe Code is as follows: <Head>
<Title> onerror Example </title>
<Script type = "text/javascript">
Window. onerror = function (){
Alert ("an error occurred! ");
}
</Script>
</Head>
<Body onload = "nonExistentFunction ()">
</Body>
</Html>

In the above Code, when loading the page, you try to call a function that does not exist, and an exception is thrown. The error message "error occurred" is displayed. However, the browser's error information is also displayed. How can we hide it in the browser? Only the onerror method returns a true value.

Copy codeThe Code is as follows: <script type = "text/javascript">
Window. onerror = function (){
Alert ("an error occurred !");
Return true;
}
</Script>

1.1 retrieve error messages

Onerror processing functions provide three types of information to determine the exact nature of an error:
I) error message-the browser displays the same information for a given error
Ii) URL -- in which file an error occurred
Iii) row number-the row number with an error in the given URL.Copy codeThe Code is as follows: window. onerror = function (sMessage, sUrl, iLine ){
Alert ("an error occurred! \ N "+ sMessage +" \ nURL: "+ sUrl +" \ nLine Number: "+ iLine );
Return true;
}

1.2 image loading error

The window object is not the only object that supports onerror event processing functions. It also supports image objects. When an image fails to be loaded due to reasons such as the file does not exist, the error event is triggered on the image. For example:Copy codeThe Code is as follows:

In the preceding example, the onerror event handler function is directly allocated in HTML. Because noexist.gif does not exist, a warning box is displayed, prompting you. Of course, you can also use scripts to allocate event processing functions. Before setting the src feature of an image, you must wait for the page to load completely. For example:Copy codeThe Code is as follows: <Head>
<Title> Image Error Test </title>
<Script type = "text/javascript">
Function handleLoad (){
Document. images [0]. onerror = function (){
Alert ("An error occurred while loading the image! ");
};
Document. images [0]. src = "amigo.jpg ";
}
</Script>
</Head>
<Body onload = "handleLoad ()">

<Body>
</Html>

Note: Unlike the onerror event processing function of the window object, the onerror event of the image does not have any parameters for additional information.

1.3 syntax error handling

Onerror event processing functions can not only handle exceptions, but also handle syntax errors.
First, the event handler function must be the first code on the page, because if a syntax error occurs before the event handler function is set, the event handler function is useless. Remember, syntax errors stop code execution completely. For example:Copy codeThe Code is as follows: <Head>
<Title> onError Example </title>
<Script type = "text/javascript">
Alert ("Syntax error .";
Window. onerror = function (sMessage, sUrl, iLine ){
Alert ("An error occurrred: \ n" + sMessage + "\ nURL:" + sUrl + "\ nLine Number:" + iLine );
Return true;
}
</Script>
</Head>
<Body onload = "nonExistentFunction ()">
</Body>
</Html>

Because the highlighted line of code (which contains the error syntax) appears before the onerror event handler function is assigned, the browser reports this error directly. The code after the error is no longer interpreted (because the thread has exited), so the nonExistentFunction () is called when the load event is released, and the browser reports this error. The book says that if you rewrite this page and place the assignment of onerror event handler before a syntax error, two warning boxes will appear: one showing a syntax error and the other displaying an exception. However, two errors are reported in the same test results, and the information in the onerror event is not displayed.

The main problem with using the onerror event to handle functions is that it is part of the BOM, so there is no standard to control its behavior. Therefore, different browsers use this event to handle errors. For example, when an error occurs in IE, the normal code will continue to be executed, all variables and data are retained and can be accessed through the onerror event processing function. In Mozilla, normal code execution ends, and all variables and data before errors occur are destroyed.

2. try... catch Method

The third edition of ECMPScript introduces try... Catch statement. The basic syntax is as follows:Copy codeThe Code is as follows: try {
// Code
[Break;]
} Catch ([exception]) {
// Code
[Break;]
} [Finally {
// Code
}]

For example:Copy codeThe Code is as follows: try {
Window. openFile1 ();
Alert ("successfully calling the openFile1 method ");
} Catch (exception ){
Alert ("exception occurred! ");
} Finally {
Alert ("try .. catch test ended! ");
}

Unlike Java, the ECMAScript standard is... There can only be one catch statement in a catch statement. Because JavaScript is a weak language, it cannot specify a specific type of exception in a catch clause. Regardless of the error type, the same catch statement processes the error. Mozilla has extended it and can add multiple catch statements. However, it is not recommended because only Mozilla can use it.

Finally is used to include the code to be executed regardless of whether an exception occurs. This is useful for closing open links and releasing resources.

2.1 nested try... catch statement

An error also occurs in the catch clause in the try... catch statement. In this case, you can use nested try... catch statements. Example:Copy codeThe Code is as follows: try {
Eval ("a ++ B ");
} Catch (oException ){
Alert ("an error occurred! ");
Try {
Var aError = new Array (1000000000000000000000000000000000000000 );
} Catch (exception ){
Alert ("an error occurred in the catch clause! ");
}
} Finally {
Alert ("completed ")
}

2.2 Error object

When an Error occurs, JavaScript has an Error base class for throw. It has two features:
I) name -- a string of the Error Type
Ii) message -- the actual error message
The name of the Error object corresponds to its class, which can be one of the following values:
EvalError: the error occurs in the eval () function;
RangeError: the numeric value exceeds the JavaScript representation range;
ReferenceError: Invalid reference is used;
SyntaxError: A syntax error occurs in eval () function calls. Other increasingly errors are reported by the browser. try... Catch processing;
TypeError: the type of the variable is not expected;
URIError: an error occurs in the encodeURI or decodeURI function.

2.3 identify error types

Although each try... catch statement can have only one catch clause, there are two main methods to determine the types of errors thrown. First, use the name feature of the Error object:Copy codeThe Code is as follows: try {
Eval ("a ++ B ");
} Catch (oException ){
If (oException. name = "SyntaxError "){
Alert ("SyntaxError occurred! ");
} Else {
Alert ("other errors occurred! ");
}
}

Second, use the instanceof operator and use different wrong class names:Copy codeThe Code is as follows: try {
Eval ("a ++ B ");
} Catch (oException ){
If (oException instanceof SyntaxError ){
Alert ("SyntaxError occurred! ");
} Else {
Alert ("other errors occurred! ");
}
}

2.4 throw an exception.

Introduced in the third edition of ECMAScript, it is used to throw an exception purposefully. The error object can be a string, number, Boolean value, or actual object, you can also throw an Error object (the constructor has only one function, that is, the Error message ). For example:Copy codeThe Code is as follows: throw new Error ("Error generated! ");

Both the errors thrown by the developer and those thrown by the browser are captured in try... catch. For example:Copy codeThe Code is as follows: function addTwoNumber (a, B ){
If (arguments. length <2 ){
Throw new Error ("two numbers are required! ");
}
}
Try {
Result = addTwoNumber (90 );
} Catch (oException ){
If (oException instanceof SyntaxError ){
Alert ("SyntaxError:" + oException. message );
} Else if (oException instanceof Error ){
Alert (oException. message );
}
}

Iii. debugging skills

Most browsers now come with debugging tools, which are enough in most cases. In addition, IETest can be used in IE and FireBug in FireFox.

Author: Artwl
Source: http://artwl.cnblogs.com

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.