JavaScript Advanced Programming Reading notes (20) JS error handling _javascript Techniques

Source: Internet
Author: User
Tags numeric value
I. Classification of Errors

1, syntax error: Also known as parsing errors, occurs in the traditional language of the compilation, in JavaScript occurs in the interpretation. These errors are caused directly by unexpected characters in the code, and then cannot be compiled/interpreted directly. You cannot continue executing code when a syntax error occurs. In JavaScript, code that is only in the same thread is affected by syntax errors. Code in other threads and other externally referenced files can continue if they do not rely on code that contains errors.
2. Run-time error: Also known as Exception (exception, after compile/interpreter). At this point, the problem is not the syntax of the code, but the attempt to complete an operation that is illegal in some cases. Exceptions affect only the threads that occur, and other JavaScript threads can continue to perform normally.

Second, error handling


JavaScript provides two ways to handle errors: The OnError event handler function in the BOM and the Try...catch method in ECMAScript.
1. onerror event handler function
It is the first mechanism 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 code as follows:

<title>onerror example</title>
<script type= "Text/javascript" >
Window.onerror = function () {
Alert ("An error has occurred!") ");
}
</script>
<body onload= "nonexistentfunction ()" >
</body>


In the preceding code, an exception is thrown when you try to invoke a function that does not exist when the page is loaded. The error message "Error occurred" pops up. However, the browser's error message is also displayed, how to hide it in the browser, only OnError method to return a true.

Copy Code code as follows:

<script type= "Text/javascript" >
Window.onerror = function () {
Alert ("An error has occurred!") ”);
return true;
}
</script>


1.1 Removing error messages

The OnError processing function provides three kinds of information to determine the exact nature of the error:
i) error message-The browser will display the same information for a given error
II) url--in which file an error occurred
III) line number--the line number where the error occurred in the given URL.
Copy Code code as follows:

Window.onerror = function (smessage, sURL, iline) {
Alert ("An error has occurred!") \ n "+ smessage +" \nurl: "+ surl +" \nline number: "+ iline);
return true;
}


1.2 Image Load Error

The Window object is not the only object that supports the OnError event handler function, it also provides support for image objects. The error event is triggered on this image when an image is not successfully loaded because the file does not exist. For example:
Copy Code code as follows:



The previous example allocates the OnError event handler directly in HTML. Because Noexist.gif does not exist, a warning box will be popped to prompt the user. Of course, you can also assign event handlers by script, and you must wait for the page to load completely before setting the SRC feature of the image, for example:
Copy Code code as follows:

<title>image Error Test </title>
<script type= "Text/javascript" >
function Handleload () {
Document.images[0].onerror = function () {
Alert ("An error occurred while loading the picture!") ");
};
DOCUMENT.IMAGES[0].SRC = "Amigo.jpg";
}
</script>
<body onload= "Handleload ()" >

<body>

Note: Unlike the OnError event handler function for the Window object, the OnError event for image does not have any parameters for additional information.

1.3 Handling syntax errors

The OnError event handler not only handles exceptions, it also handles syntax errors, and only it can handle them.
First, the event handler must be the first occurrence of the code on the page, because the event handler is useless if the syntax error occurs before the event handler function is set. Remember that syntax errors completely stop code execution. For example:
Copy Code code as follows:

<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>
<body onload= "nonexistentfunction ()" >
</body>

Because the highlighted line of code (with error syntax inside) appears before assigning the OnError event handler, the browser reports the error directly. The code after the error is no longer interpreted (because the thread has exited), so call Nonexistentfunction () when the Load event Jie Fa, and the browser will also report the error. The book says that if you rewrite this page and put the OnError event handler assignment before the syntax error, there will be two warning boxes: one to display a syntax error and another to display an exception. But the results of my tests are the same. Two errors do not show the information in the OnError event.

The main problem with using the OnError event handler 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 in a significantly different way, eg, in IE, when the error event, the normal code will continue to execute, all the variables and data are preserved, and can be accessed through the OnError event handler function. In Mozilla, normal code execution ends, and the variables and data before all errors are destroyed.

2, Try...catch Way

Ecmpscript The third edition, introduced the Try...catch statement. The basic syntax is as follows:
Copy Code code as follows:

try{
Code
[Break;]
catch ([exception]) {
Code
[Break;]
} [finally{
Code
}]

For example:
Copy Code code as follows:

try {
Window.openfile1 ();
Alert ("Successful invocation of OpenFile1 method");
} catch (Exception) {
Alert ("An exception has occurred!") ");
finally {
Alert ("Try.. Catch Test end! ");
}

Unlike Java, the ECMAScript standard can have only one catch statement in a try...catch statement, because JavaScript is a weakly typed language, and there is no way to specify the specific type of exception in a catch clause. Regardless of the type of error, it is handled by the same catch statement. Mozilla expands it to add more catch statements, but it is not recommended because it is available only to Mozilla.

Finally is used to include code that is executed regardless of whether an exception occurred, which is useful for closing open links and releasing resources.

2.1 Nested Try...catch statements

An error also occurs in the catch clause in the Try...catch statement. At this point, you can use the nested Try...catch statement. Example:
Copy Code code as follows:

try {
Eval ("A + + B");
} catch (Oexception) {
Alert ("An error has 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 throwing. It has two features:
i) name--a string representing the type of error
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 range that JavaScript can represent;
Referenceerror: The use of illegal references;
SyntaxError: A syntax error occurred in the eval () function call, and other more errors were reported by the browser and could not be processed through try...catch;
TypeError: The type of the variable is not expected;
Urierror: An error occurred in the encodeURI or decodeURI function.

2.3 Judging the type of error

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

try {
Eval ("A + + B");
} catch (Oexception) {
if (Oexception.name = "SyntaxError") {
Alert ("Occurrence of syntaxerror!");
} else {
Alert ("Other error occurred!");
}
}

The second type uses the instanceof operator and uses the class name of the different error:
Copy Code code as follows:

try {
Eval ("A + + B");
} catch (Oexception) {
if (oexception instanceof syntaxerror) {
Alert ("Occurrence of syntaxerror!");
} else {
Alert ("Other error occurred!");
}
}


2.4 Throwing an exception

Introduced in the ECMAScript third edition, for purposeful throw exceptions, the thrown error object can be a string, numeric, Boolean, or actual object, or you can throw an Error object (its constructor has only one function, that is, an error message). Such as:
Copy Code code as follows:

throw new error ("Error generation!") ");

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

function Addtwonumber (A, b) {
if (Arguments.length < 2) {
throw new Error ("need to pass in two digits!");
}
}
try {
result = Addtwonumber (90);
} catch (Oexception) {
if (oexception instanceof syntaxerror) {
Alert ("SyntaxError:" + oexception.message);
else if (oexception instanceof Error) {
alert (oexception.message);
}
}


Third, debugging skills

Now most of the browsers have their own debugging tools, most of the time is enough, in addition to IE under the Ietest,firefox can also be used under the Firebug.

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

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.