Javascript advanced programming Reading Notes (20): 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 causedCodeAnd cannot be compiled directly./Description.When a syntax error occurs, the Code cannot be executed. InJavascriptOnly 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:It is also called an exception (Exception, During compilation/After 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.JavascriptThe thread 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 one to assistJavascriptError handling mechanism. When an exception occurs on the page,ErrorThe event isWindowObject. For example:

 < Html  >      <  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 on the browser?OnerrorMethod returnsTrueYou can.

<ScriptType= "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.

 
Window. onerror =Function(Smessage, Surl, iline) {alert ("An error occurred! \ N "+ smessage +" \ nurl: "+ Surl +" \ nline number: "+Iline );Return True;}

1.2 image loading error

WindowThe object is not unique.OnerrorThe object of the event processing function, which also supports image objects. When an image fails to be loaded due to reasons such as the file does not exist,ErrorThe event is triggered on this image. For example:

<IMGSRC= "Noexist.gif"Onerror= "Alert ('error occurred when loading the image ')"/>

In the preceding exampleHtmlMedium allocationOnerrorEvent processing functions. Because noexist.gif does not exist, a warning box is displayed, prompting you. Of course, you can also use the script to allocate event processing functions.SRCBefore the feature, you must wait for the page to be fully loaded, for example:

 <  Html  >      <  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 ()"  >         <  IMG  />     <  Body  >  </  Html  > 

Note:: AndWindowObjectOnerrorDifferent event processing functions,ImageOfOnerrorThe event 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:

 <  Html  >  < 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

EcmpscriptThe third edition introducesTry... CatchStatement. The basic syntax is as follows:

 
Try{//Code[Break;]}Catch([Exception]) {//Code[Break;]} [Finally{//Code}]

For example:

Try{Window. openfile1 (); alert ("The openfile1 method is successfully called");}Catch(Exception) {alert ("An exception occurred! ");}Finally{Alert ("Try .. catch test is over! ");}

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:

Try{Eval ("A ++ B");}Catch(Oexception) {alert ("An error occurred! ");Try{VaRAerror =NewArray (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 range that can be expressed by JavaScript;

Referenceerror: Invalid reference is used;

Syntaxerror: Syntax errors occur in eval () function calls. More and more other errors are reported by the browser. Try... Catch processing;

Typeerror: The variable type is not expected;

Urierror: An error occurred 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:

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:

Try{Eval ("A ++ B");}Catch(Oexception ){If(OexceptionInstanceofSyntaxerror) {alert ("Syntaxerror occurred! ");}Else{Alert ("Other errors occurred! ");}}

2.4 throw an exception.

InEcmascriptIntroduced in the third edition to throw an exception purposefully. The error object can be a string, number, Boolean value, or actual object.ErrorObject (the constructor has only one function, that is, the error message ). For example:

 
Throw NewError ("error generated !");

Both the errors thrown by the developer and those thrown by the browser are captured in try... catch. For example:

 Function  Addtwonumber (a, B ){  If (Arguments. Length <2 ){  Throw   New Error ("two numbers are required! " );}}  Try  {Result = Addtwonumber (90 );}  Catch  (Oexception ){  If (OexceptionInstanceof  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.Ietest can also be used in IE and firebug in Firefox.

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.