Exception Handling Methods in JS

Source: Internet
Author: User

Exception Handling Methods in JS

When writing JavaScript code, we will inevitably encounter some code errors and need to find them out. Sometimes, we are afraid that the user experience may be poor due to js problems. Here are some solutions.

Js Fault-Tolerant statements, that is, js errors do not prompt errors (prevent the browser from having a yellow triangle symbol in the lower right corner, or the user experience is poor)

 

The Code is as follows:

Window. onerror = function () {return true ;}

 

 

 

The following is an example of how to retrieve js exception information for developers.

 

1, try... catch...

 

The Code is as follows:

<Script type = "text/javascript">

Var txt = ""

Function message ()

{

Try

{

Adddlert ("Welcome guest! ")

}

Catch (err)

{

Txt = "This page contains errors. Nn"

Txt + = "click" OK "to continue viewing this page, n"

Txt + = "click" cancel "to return to the home page. Nn"

If (! Confirm (txt ))

{

Document. location. href = "/index.html"

}

}

}

</Script>

 

 

2, throw

 

The Code is as follows:

<Script type = "text/javascript">

Var x = prompt ("Enter the number between 0 and 10 :","")

Try

{

If (x> 10)

Throw "Err1"

Else if (x <0)

Throw "Err2"

Else if (isNaN (x ))

Throw "Err3"

}

Catch (er)

{

If (er = "Err1 ")

Alert ("error! The value is too large! ")

If (er = "Err2 ")

Alert ("error! The value is too small! ")

If (er = "Err3 ")

Alert ("error! This value is not a number! ")

}

</Script>

 

 

3, onerror:

 

The Code is as follows:

<Script type = "text/javascript">

Onerror = handleErr

Var txt = ""

 

Function handleErr (msg, url, l)

{

Txt = "This page contains errors. Nn"

Txt + = "error:" + msg + "n"

Txt + = "URL:" + url + "n"

Txt + = "row:" + l + "nn"

Txt + = "click" OK "to continue. Nn"

Alert (txt)

Return true

}

 

Function message ()

{

Adddlert ("Welcome guest! ")

}

</Script>

 

 

 

Exception Handling in js

 

In JavaScript, try... catch can be used for exception handling. For example:

 

Try {foo. bar ();} catch (e) {alert (e. name + ":" + e. message );}

Currently, the possible system exceptions include the following 6 types:

 

EvalError: raised when an error occurs executing code in eval ()

RangeError: raised when a numeric variable or parameter is outside of its valid range

ReferenceError: raised when de-referencing an invalid reference

SyntaxError: raised when a syntax error occurs while parsing code in eval ()

TypeError: raised when a variable or parameter is not a valid type

URIError: raised when encodeURI () or decodeURI () are passed invalid parameters

The preceding six exception objects are inherited from Error objects. They both support the following two constructor methods:

 

New Error (); new Error ("exception information ");

The method for manually throwing an exception is as follows:

 

The Code is as follows:

Try {

Throw new Error ("Whoops! ");}

Catch (e ){

Alert (e. name + ":" + e. message );}

 

 

To determine the type of the exception information, you can make a judgment in catch:

 

 

 

The Code is as follows:

Try {

Foo. bar ();

} Catch (e ){

If (e instanceof EvalError ){

Alert (e. name + ":" + e. message );

} Else if (e instanceof RangeError ){

Alert (e. name + ":" + e. message );}

// Etc

}

 

 

Error has the following attributes:

 

Description: Error description (IE only ).

FileName: indicates the file name with an error (available only for Mozilla ).

LineNumber: Number of wrong lines (available only for Mozilla ).

Message: error message (description in IE)

Name: Error type.

Number: Error Code (IE only ).

Stack: Error Stack information similar to the stack Trace in Java (available only by Mozilla ).

Therefore, to better understand the error information, we can change the catch part to the following form:

 

 

The Code is as follows:

Try {

Foo. bar ();

} Catch (e ){

If (browserType! = BROWSER_IE ){

Alert ("name:" + e. name + "message:" + e. message + "lineNumber:" + e. lineNumber + "fileName:" + e. fileName + "stack:" + e. stack );

} Else {

Alert ("name:" + e. name + "errorNumber:" + (e. number & 0 xFFFF) + "message:" + e. message ");}}"

 

 

The throw command in JavaScript can actually throw any object, and we can accept this object in catch. For example:

 

 

The Code is as follows:

Try {

Throw new Date (); // throw the current time object} catch (e) {alert (e. toLocaleString (); // display the current time in local format

}

 

 

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.