Exception handling in JavaScript

Source: Internet
Author: User
Tags object exception handling finally block
Javascript| Exception Handling problem:
You want to handle a script error (exception) outside of the user view to prevent the browser from reporting an error message to the user.

Solution:
A quick-and-dirty (fast-food), backward-compatible way: Place the following code in the function donothing () {return true;}
Window.onerror = donothing; This does not prevent a compile-time script error (such as a syntax error found by the interpreter when the page loads), nor does it reveal to you where the code is lurking in error. So only your code has been fully tested to use this method, in the test, to remove the code.

In IE5 and Netscape6 and their subsequent versions, you can use more error (exception) handling. To prevent early browsers from executing these special scripts, set the Language property of the <script> label where the statements are located to JavaScript1.5 (language= "JavaScript1.5").
Encapsulates statements that may cause or throw exceptions in a try...catch...finally structure. Executes the statement in the try block, which contains code that might have an exception, and executes the code in the catch block, regardless of whether an exception occurs, and then unconditionally executes the statement of the finally block:
<script language= "javascript1.5" >
Try
{
Trystatements
}
catch (ex)
{
catchstatements;
}
Finally
{
finallystatements;
}
</script>

Each thrown exception produces an instance of an Error object that can be used as a parameter to a catch clause, such as the ex parameter of the preceding code, where the statement in the CATCH clause can view the properties of the object for more information. So far, only two attributes have been officially recognized in the ECMAScript standard, that is, message and name. Some browsers implement more properties:
Property
The support of IE Support for NN Describe
Description
5
N/A
Description information for the exception
FileName N/A
6 URI of the file where the script throws the exception
LineNumber
N/A
6
The line number of the code that threw the exception
Message
5.5
6
Description information for the exception (ECMA)
Name
5.5
6
Exception type (ECMA)
Number
5
N/A
Exception code for IE unique

For example, we could write a piece of code like this:
Try
{
COLORS[2] = "red";
}
catch (E)
{
Alert ("An exception occured in the script". Error Name: "+ e.name
+ ". Error message: "+ e.message";
To access an element with the colors index of 2, an exception is thrown: colors is not defined. The statement in the CATCH block tells the user some simple information. This looks good, and you can use this method to show the user some more friendly information.

And so on, notice that the catch statement here catches all types of exceptions. Think in C #, we need to try to avoid capturing common exception type exceptions because it's too generic, and we sometimes want to take different approaches to different types of exceptions. Here too, fortunately, there are some specific types of exceptions in JavaScript. For example, for the exception that the above code throws, we can write this:
Try
{
COLORS[2] = "red";
}
catch (E)
{
if (e instanceof typeerror)
{
Alert ("An exception occured in the script". Error Name: "+ e.name
+ ". Error message: "+ e.message";
}
After an exception is caught, the exception type is judged, only the exception of the TypeError type is handled, and the other types are ignored.
JavaScript has six basic types of exceptions:
    • Evalerror: Thrown when the eval () function is invoked incorrectly;
    • Rangeerror: Thrown when the value of a numeric variable is outside its range;
    • Referenceerror: Thrown when an invalid reference is used;
    • SyntaxError: Syntax errors are thrown when parsing JavaScript code;
    • TypeError: Thrown when an unexpected type is encountered;
    • Urierror: Thrown when the encodeURI () or decodeURI () function is incorrectly used.
The following code demonstrates the flow of nested exception handling:
Try
{
Print ("Outer try running ...");
Try
{
Print ("Nested try running ...");
Throw "an error";
}
catch (E)
{
Print ("Nested catch caught" + e);
Throw e + "re-thrown";
}
Finally
{
Print ("Nested finally is running ...");
}
}
catch (ex)
{
Print ("Outer catch caught" + ex);
}
Finally
{
Print ("Outer finally Running");
}

function print (s)
{
document.write (s);
This uses the throw statement to throw an exception, and the throw statement can throw arbitrary objects.
The output results are:
Outer try running..
    Nested try running...
    Nested catch caught an error
    Nested finally is running...
    Outer catch caught an error re-thrown
    Outer finally running


Exception information should not be visible to the user. Use the Message property to determine how exceptions are handled.
You can also create your own exception handling mechanism by intentionally throwing exceptions in your script. Look at the following example:
function Processnumber (Inputfield)
{
Try
{
var inpval = parseint (Inputfield.value, 10);
if (isNaN (Inpval))
{
var msg = "Please enter a number!";
var err = new Error (msg);
if (!err.message)
{
Err.message = msg;
}
throw err;
}
}
catch (E)
{
alert (e.message);
Inputfield.focus ();
Inputfield.select ();
}
Detects the value of a form field in a try block, and if not, throws a custom exception that the catch block captures and handles accordingly.


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.