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

JavaScript error handling_javascript skills

WBOY
Release: 2016-05-16 16:16:02
Original
1578 people have browsed it

1. Error classification

1. Syntax error

Also known as parsing errors, which occur at compile time in traditional programming languages, and at interpret time in JavaScript, these errors are directly caused by unexpected characters in the code, which then cannot be directly compiled/interpreted, eg, in A line of code produced a syntax error due to a missing right parenthesis. 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 known as exception (exception, at compile time/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. eg.

window.openMyFile();

Because the openMyFile() method does not exist, the browser will return an exception. The exception only affects the thread where it occurred, and other JavaScript threads can continue to execute normally.

2. Handling errors

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

Copy code The code is as follows:

                                                                                                                   
                                                                                                                                                                                          onerror example
                                  
        

         
        


In the above code, if you try to call a non-existent function when the page is loading, an exception will be thrown. 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) Remove 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 message;

ii) URL - in which file the error occurred;

Line number – The line number in the given URL where the error occurred.

See the following example for the access method:

Copy code The code is as follows:


2) Image loading error

The window object is not the only object that supports onerror event handling functions, it also provides support for image objects. When an image fails to load successfully due to reasons such as file non-existence, the error event is triggered on the image. Let’s look at an example:

The above example directly assigns the onerror event handler function in HTML. Of course, event processing functions can also be assigned through scripts. Before setting the src characteristics of the image, you must wait for the page to be fully loaded. The code is as follows:

Copy code The code is as follows:



                                                                                                                                                     

        
                                                                                                                                                                                                                 



Note: Unlike the onerror event handler of the window object, the onerror event of the image has no additional information parameters.
3) Handle syntax errors

onerror can also handle syntax errors. But one thing must be noted, the event handler function must be the first code that appears on the page, because if the syntax error occurs before the event handler function is set, the event handler function will be useless.

Note: Syntax errors will completely stop the execution of the code.

Note: The main problem with using the onerror event handler is that it is part of the BOM, so there is no standard that can control its behavior. 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, the normal code will continue to execute, and all variables and data will be retained and can be processed through the onerror event. Function access. In Mozilla, normal code execution ends, and all variables and data before the error occurs are destroyed.

2. 

try…catch statement

The third edition of ECMPScript introduces the try...catch statement. Eg.

Copy code

The code is as follows: try {           window.openFile1();
alert("openFile1 method successfully called");
} catch (exception) {
alert("An exception occurred!");
} finally {
alert("try..catch test is over!");
}



Unlike Java, the ECMAScript standard can only have one catch statement in the try...catch statement. Because JavaScript is a weakly typed language, there is no way to specify the specific type of exception in the catch clause. Regardless of the type of error, it is handled by the same catch statement. However, Mozilla has extended it to add multiple catch statements, which is 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.

1) Nested try…catch statement

is used to handle errors in the catch clause. Let us look at an example. The code is as follows:

Copy code

The code is as follows: try { eval("a b");
} catch(oException) {
alert("An error occurred!");
Try {
var aError = new Array(100000000000000000000000000000000000000);
} catch(exception) {
alert("An error occurred in the catch clause!");
}
} finally{
alert("Completed")
}

2) Error object

When an error occurs, JavaScript has an Error base class for throwing. It has two features:

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:

EvalError: The error occurred in the eval() function;

RangeError: Numeric value exceeds the range that JavaScript can represent;

ReferenceError: Illegal reference used;

SyntaxError: A syntax error occurred in the eval() function call. Other errors are reported by the browser and cannot be handled by try...catch;

TypeError: The type of variable is not expected;

URIError: An error occurred in the encodeURI or decodeURI function.

3) Determine the type of error

The following two methods can be used to determine the error type. The first one is based on the name attribute of the exception, as follows:

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, the code is as follows:

Copy code The code is as follows:

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

4) Throw statement that throws exception

Introduced in the third edition of ECMAScript, it is used to throw exceptions for purpose. The error object thrown can be a string, number, Boolean value or actual object. It can also throw an Error object (its constructor has only one function, i.e. error message). eg1. throw new Error("An error occurred!");

eg2.

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);
}
}

The above is all the content described in this article, I hope you guys will like it.

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!