JavaScript Learning notes-error handling

Source: Internet
Author: User

Description: See chapter 14th of Advanced JavaScript programming.

A Error classification

1 . Syntax error

Also known as parsing errors, which occur at compile time in a traditional programming language, when interpreted in JavaScript, these errors are caused directly by unexpected characters in the code, and cannot be directly compiled/interpreted, eg, where a line of code is missing a closing parenthesis, resulting in a syntax error. When a syntax error occurs, you cannot continue executing the code. In JavaScript, only code in the same thread is affected by a syntax error. Code in other threads and other externally referenced files can continue if you do not rely on the code that contains the error.

2 . Run-time error

Also known as an exception (exception, after the compile-time/interpreter). At this point, the problem is not the syntax of the code, but the attempt to complete an operation, in some cases, is illegal. eg.

Window.openmyfile ();

The browser returns an exception because the Openmyfile () method does not exist. Exceptions affect only the threads that occur, and other JavaScript threads can continue to perform normally.

Two Handling Errors

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 fires on the Window object. Eg.

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

In the preceding code, an exception is thrown when a page load is attempted to invoke a function that does not exist. A "error occurred" error message pops up. However, the browser error message is also displayed, how to hide it on the browser, just OnError method return a true.

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

1 ) to remove the error message

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 the error occurred;

Line number-the line number where the error occurred in the given URL.

See the following examples of access methods:

<script type= "Text/javascript" >
Window.onerror = function (smessage, sURL, sline) {
Alert ("An error has occurred! \ n "+ smessage +" \nurl: "+ surl +" \nline number: "+ sline);
return true;
}
</script>

2 ) Image Load Error

The Window object is not the only object that supports the OnError event handler, and it also provides support for image objects. When an image fails to load successfully due to a file not being present, the error event is triggered on this image. Let's look at an example:

The previous example assigns the OnError event handler directly in HTML. Of course, you can also allocate event handlers by script, before setting the SRC attribute of the image, you must wait for the page to fully load, the code is as follows:

<HTML>
    <Head>
           <title>ImageError Test</title>
        <Scripttype= "Text/javascript" >
                  functionHandleload () {
Document.images[0].onerror =function() {
Alert ("there was an error loading the picture! ");
};

document.images[0].src = "Amigo.jpg";
}
              </Script>
       </Head>
       <Bodyonload="handleload () ">
              <img/>
       <Body>
</HTML>

Note : Unlike the OnError event handler function of the Window object, the OnError event of the image has no parameters for any additional information.

3 ) Handling syntax errors

OnError can also handle syntax errors. However, it is important to note that the event handler must be the first code that appears on the page because the event handler is useless if the syntax error occurs before the event handler is set.

Note: syntax errors completely stop the execution of the code.

Description: 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 the error in a distinctly different way, eg, when an error event occurs in IE, the normal code will continue to execute, all variables and data are preserved, and can be accessed through the OnError event handler function. In Mozilla, normal code execution will end, and all the variables and data before the error occurs are destroyed.

2. Try... catch statement

Ecmpscript Third Edition, introduced the Try...catch statement. Eg.

try {
Window.openfile1 ();
Alert ("Successful call to OpenFile1 method");
} catch (Exception) {
Alert ("An exception occurred! ");
} finally {
Alert ("Try". Catch Test finished! ");
}

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 indicate 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 are not recommended for this use.

Finally, which contains code that executes regardless of whether an exception occurred, is useful for closing open links and freeing resources.

1 ) nested Try...catch statements

To handle the error in the catch clause, let's take a look at an example with the following code:

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 ) Error Object

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

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 occurred 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 has occurred in the Eval () 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: An error occurred in the encodeURI or decodeURI function.

3 ) determine the type of error

There are two ways to determine the type of error, the first based on the Name property of the exception, as follows:

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

The second uses the instanceof operator, the code is as follows:

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

4 throws an exception to the throw statement

Introduced in the third edition of ECMAScript, for purposeful throwing exceptions, the thrown error object can be a string, a number, a Boolean value, or an actual object, or an Error object (whose constructor has only one function, that is, an error message). Eg1. throw new error ("Error generated! ”);

EG2.
function Addtwonumber (A, b) {

if (Arguments.length < 2) {

throw new Error ("need to pass in two numbers!");

}

}

try {
result = Addtwonumber (90);
} catch (Oexception) {
if (oexception instanceof syntaxerror) {
Alert ("SyntaxError:" + oexception.message);
} else if (oexception instanceof Error) {
alert (oexception.message);
}
}

JavaScript Learning notes-error handling

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.