Home > Web Front-end > JS Tutorial > body text

JavaScript Advanced Programming Reading Notes (20) js error handling_javascript skills

WBOY
Release: 2016-05-16 17:50:50
Original
1137 people have browsed it
1. Error classification

1. Syntax error: also known as parsing error, which occurs during compilation of traditional languages ​​and during interpretation in JavaScript. These errors are caused directly by unexpected characters in the code, which then cannot be compiled/interpreted directly. When a syntax error occurs, code execution cannot continue. In JavaScript, only code within the same thread is affected by syntax errors. Code in other threads and in other externally referenced files can continue to execute if it does not depend on the code containing the error.
 2. Runtime error: also called exception (exception, during compilation/after interpreter). At this point, the problem is not with the syntax of the code, but with trying to complete an operation that is illegal in some cases. The exception only affects the thread where it occurred, and other JavaScript threads can continue to execute normally.

2. Error handling


JavaScript provides two ways to handle errors: the onerror event handler method in BOM and the try...catch method in ECMAScript .
1. Onerror event handling function
It is the first mechanism used to assist JavaScript in handling errors. When an exception occurs on the page, the error event is triggered on the window object. For example:

Copy code The code is as follows:



onerror Example







In the above code, an exception will be thrown when trying to call a non-existent function when the page is loaded. An "An error occurred" error message pops up. However, the browser's error message is also displayed. How to hide it on the browser? Just return a true from the onerror method.

Copy code The code is as follows:




1.1 Get the error message

The onerror handler provides three types of information to determine the exact nature of the error:
i) Error message - for a given error, the browser will display the same Information
ii) URL - In which file the error occurred
iii) Line number - The line number in the given URL where the error occurred.
Copy code The code is as follows:

window.onerror = function(sMessage, sUrl, iLine) {
alert("An error occurred! " sMessage "nURL:" sUrl "nLine Number:" iLine);
return true;
}


 1.2 Image loading error

window object It is not the only object that supports the onerror event handler. It also provides support for image objects. When an image fails to load successfully due to reasons such as the file does not exist, the error event is triggered on the image. For example:
Copy code The code is as follows:
Allocate event processing functions through scripts. Before setting the src attribute of the image, you must wait for the page to be fully loaded, for example:



Copy codeImage error test








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

1.3 Handling syntax errors

The onerror event handler can not only handle exceptions, it can also handle syntax errors, and only it can handle them.
First of all, the event handler must be the first code that appears on the page, because if the syntax error occurs before setting the event handler, the event handler will be useless. Remember, syntax errors can completely stop the execution of your code. For example:
Copy code The code is as follows:


onError Example






Because it stands out The line of code shown (with the error syntax in it) appears before the onerror event handler is dispatched, so the browser directly reports the error and the code after the error is no longer interpreted (because the thread has already exited). When nonExistentFunction() is called when the load event is fired, the browser will also report this error. The book says that if you rewrite this page and place the assignment of the onerror event handler before the syntax error, two warning boxes will appear: one displays Syntax error, another display exception, but the result of my test is still the same, two errors are reported, and the information in the onerror event is not displayed.

The main problem with using the onerror event handler is that it is a BOM. Therefore, there are obvious differences in the way different browsers use this event to handle errors. For example, when an error event occurs in IE, normal code will continue to execute. The variables and data are retained and can be accessed through the onerror event handler. In Mozilla, normal code execution will end, and all variables and data before the error occurs will be destroyed. 2. try...catch method

The third edition of ECMPScript introduces the try...catch statement. The basic syntax is as follows:


try{
//code
[break;]
} catch ([exception]) {
//code
[break;]
} [finally{
//code
}]


For example:


try {
window.openFile1();
alert("The openFile1 method was called successfully");
} catch (exception) {
alert("An exception occurred! ");
} finally {
alert("try..catch test ended!");
}


Unlike Java, the ECMAScript standard is in the try...catch statement There can only be one catch statement, because JavaScript is a weakly typed language and there is no way to specify the specific type of exception in the catch clause. No matter what type of error it is, it is handled by the same catch statement, which can be added. Multiple catch statements, but because only Mozilla can use them, they are not recommended.

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

 2.1 Nested try...catch statement

In the catch clause of the try...catch statement, an error will also occur. At this time, you can use nested try. ...catch statement. Example:


try { } >eval("a b"); 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 throwing. It has two characteristics:
i) name - a string representing the error type
ii) message - the actual error message
The name of the Error object corresponds to its class and can be one of the following values One:
EvalError: The error occurred in the eval() function;
RangeError: The numeric value exceeds the range that JavaScript can represent;
ReferenceError: An illegal reference was used;
SyntaxError: In eval() A syntax error occurred in the function call, and other errors are reported by the browser and cannot be handled by try...catch;
TypeError: The type of the variable is not expected;
URIError: Occurred in the encodeURI or decodeURI function error.

 2.3 Determining the error type

Although there can only be one catch clause in each try...catch statement, there are two main ways to determine the type of error thrown. The first one uses the name attribute of the Error object:
Copy code The code is as follows:

try {
eval("a b");
} catch(oException) {
if (oException.name = "SyntaxError") {
alert("SyntaxError occurred!");
} else {
alert("Another error occurred!");
}
}

The second one uses the instanceof operator and uses different error class names:
Copy code The code is as follows:

try {
eval("a b");
} catch(oException) {
if (oException instanceof SyntaxError) {
alert("SyntaxError occurred!");
} else {
alert("Other error occurred!");
}
}


2.4 Throwing exceptions

Introduced in the third edition of ECMAScript, it is used to throw exceptions for purpose. The error object thrown can be Strings, numbers, Boolean values ​​or actual objects can also throw Error objects (its constructor has only one function, error information). For example:
Copy code The code is as follows:

throw new Error("An error occurred!") ; 

Errors thrown by developers and errors thrown by the browser itself are captured in try...catch. For example:
Copy code The code is as follows:

function addTwoNumber(a, b) {
if (arguments.length < 2) {
throw new Error("Two numbers need to be passed in!");
}
}
try {
result = addTwoNumber(90 );
} catch(oException) {
if (oException instanceof SyntaxError) {
alert("SyntaxError:" oException.message);
} else if (oException instanceof Error){
alert(oException.message);
}
}


3. Debugging skills

Most of today’s browsers automatically Bringing debugging tools is enough in most cases. In addition, you can also use IETest under IE and FireBug under FireFox.

Author: Artwl
Source: http://artwl.cnblogs.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template