JavaScript Advanced Applications: Exception handling

Source: Internet
Author: User
Tags eval exception handling execution expression final finally block functions reference
Javascript| Advanced

In program development, programmers often face how to write code to respond to the occurrence of error events, i.e. exception handling (exception handlers). If the exception-handling code is well-designed, then the final presentation to the user will be a friendly interface. Otherwise, it will allow visitors to feel the inexplicable phenomenon of the real "accident." This article will introduce you to the exception-handling techniques for JavaScript languages in web development.

  First, what is the exception handling

The JavaScript interpreter throws exception handling when a JavaScript program takes place in the runtime, such as an array index out of bounds, a type mismatch, or a syntax error. ECMAScript defines six types of errors, in addition to that, we can use the Error object and the throw statement to create and raise custom exception handling information.

Ii. advantages of exception-handling techniques

By using exception handling techniques, we can implement a structured approach to responding to error events, separating exception handling code from normal scripting code, and ultimately enabling us to focus on writing core programs that accomplish major functions.

Iii. use of try...catch...finally to perform exception handling

In JavaScript, we use the Try...catch...finally statement to perform exception handling, that is, to catch exceptions that occur after an error has occurred, or to execute an exception resulting from a throw statement. Its basic syntax is as follows:

try {
Here is a statement that may produce an exception
catch (Error) {
Here is the statement for exception handling
finally {
Here is the exit statement
}

In the preceding code, the statements in the try block are executed first. If an error occurs in the run, the control is transferred to the statement in the catch block, where the error parameter in parentheses is passed as an exception variable. Otherwise, the statement of the Catch block is skipped and not executed. The statement in the finally block is executed, regardless of whether the statement in the catch block completes when the error occurs, or when the statement in the error try block executes.

Let's take a look at the following example:

Let's take a look at the following example:

<script language= "JavaScript" >
try {
Document.writeln ("Start executing try block statement--->")
Document.writeln ("No exception has occurred--->")
Alert (Prompt ("Enter a value:", "))
} catch (Err) {
Document.writeln ("Catch exception, start execution of Catch block statement--->");
Document.writeln ("Error name:" + err.name+ "--->");
Document.writeln ("error message:" + err.message+ "--->");
finally {
Document.writeln ("Start executing finally block statement")
}
</script>

After you execute the above code in the browser, the Input dialog box is displayed first:



We enter ABC, and then we determine that the output results are as follows:

"Start execution of Try block statement---> No exception has occurred---> caught the exception and started executing the CATCH block statement---> Error name: TypeError---> Error message: ' ABC ' not defined---> started execution finally Block Statement "

The above routines start with a try block statement, when the output information "no exception", the pop-up Input dialog box, asking the user to enter a value, when we enter the illegal information "ABC", an exception, so that the remaining try block statements will be skipped and start to execute the CATCH block statement. The Err argument at the start of the catch block is an Error object for this exception, and it has the name and message two properties. Finally, execute the statement of the finally block.

Let's run this code again and enter a correct value of 123:

You will see the following results:

We see that, as there are no errors, when the statement of a try block is executed, the CATCH block statement is skipped, a window appears displaying the input value, and finally executes the statement of the finally block.

  Iv. deformation of the try...catch...finally

The try...catch...finally statement has two kinds of variants, namely Try...catch or try...finally.

Try...catch This structure is most common, and it is executed when the control moves to the statement following the entire try...catch structure, after the execution of the TRY block statement, or after the exception executes the CATCH block statement. Take a look at the following example:

try {
Document.writeln ("Beginnng the Try Block")
Document.writeln ("No Exceptions Yet")
Create a syntax error
Eval ("6 + * 3")
Document.writeln ("finished the try block with no exceptions")
} catch (Err) {
Document.writeln ("Exception caught, executing the CATCH block")
Document.writeln ("Error name:" + err.name)
Document.writeln ("Error message:" + err.message)
}
Document.writeln ("Executing after the Try-catch statement")

In the case of a try...finally structure, the statement of the final finally block is not executed when an exception occurs because there is no catch block statement to catch the error. Therefore, this kind of structure is very rare in practical application.

  V. The manifestation of the exception: the Error object

In JavaScript, the exception appears as an Error object. The Error object has two properties: The Name property represents the type of the exception, and the message property represents the meaning of the exception. Depending on the value of these properties, we can decide how to handle the exception, such as:

function Evaltext () {
try {
Alert (eval (Prompt ("Enter JavaScript to evaluate:", ""))
} catch (Err) {
if (Err.name = = "SyntaxError") alert ("Invalid expression")
Else alert ("Cannot evaluate")
}
}

The code above will evaluate what the user has entered and then display the expression. If a Syntaxerroe type error occurs in the evaluation process, it is displayed to the user "Invalid expression", otherwise the user gets the information "cannot evaluate".

There are six kinds of error.name, as follows:

The use of Evalerror:eval () is inconsistent with the definition
Rangeerror: Value out of bounds
Referenceerror: Illegal or unrecognized reference value
SyntaxError: Syntax resolution error occurred
TypeError: Error in operand type
Improper use of Urierror:uri processing functions

  VI. Customization of exception information

The six error types described above basically cover errors that may occur when the script is run. In addition to these types, we can use the error constructor to customize the exception type with the following syntax:

Myerror = new Error (msg)

Where the msg parameter represents the value of the message property for the new exception that is defined. At the same time, we can create a new object type to act as a subtype of the error:

function Myerror (msg) {
THIS.name = "Myerror"
This.message = Msg
}
Myerror.prototype = new Error;

We can then create an instance of the custom error subclass:

Myerror = new Myerror ("My error Message")

  Vii. triggering exceptions

After you create an Error object, you can use the throw statement to trigger the appropriate exception. The syntax for throw is as follows:

Throw Errobj

Errobj must be an Error object or a subtype of the error. When an exception is triggered in the try block code, the control is transferred directly to the catch block.

In the following code, an exception is triggered in the try block, the exception is set to "oops", and then control is transferred to the CATCH block:

var s
try {
s = "One"
throw new Error ("oops")
S + + "two"
} catch (Err) {
S + + Err.message
}
S + + "three"
Alert (s)

After running, the following prompt box appears:

There are many advantages to writing code to trigger exceptions, such as favouring custom error types, quickly turning into catch block execution, and, as described below, passing errors to the outer layer in nested exceptions.

  Viii. Nested exception handling

JavaScript supports multiple levels of nested exception handling. In general, we can catch and handle errors in an internal exception-handling catch code block, and then fire the exception again, so that further processing can be done in the catch block of external exception handling. Here's a look at an example of a nested exception-handling:

var inner;
var outer;
try {
Document.writeln ("Beginning outer try block, no exceptions yet");
try{
Document.writeln ("Beginning inner try block, no exceptions yet");
Generate a reference error
Document.writeln (undefinedvariable)
Document.writeln ("Finished inner try block with no exceptions");
} catch (inner) {
Internal exception handling
Document.writeln ("Exception caught, beginning inner catch block");
Document.writeln ("Error type:" + inner.name);
Document.writeln ("Error message:" + inner.message);
throw inner;
Document.writeln ("No exceptions thrown in the inner Catch block");
finally {
Document.writeln ("Executing inner finally block");
}
Document.writeln ("finished outer try block with no exceptions");
} catch (outer) {
External exception handling
Document.writeln ("Exception caught, beginning outer catch block");
Document.writeln ("Error type:" + outer.name);
Document.writeln ("Error message:" + outer.message);
finally {
Document.writeln ("Executing outer finally block");
}

The output after execution is as follows:

Beginning outer try block, no exceptions yet
Beginning inner Try block, no exceptions yet
Exception caught, beginning inner catch block
Error Type:referenceerror
Error message:undefinedvariable is not defined
Executing inner finally block
Exception caught, beginning outer catch block
Error Type:referenceerror
Error message:undefinedvariable is not defined
Executing outer finally block

The advantage of nesting exception handling is that it enables us to handle errors in a phased manner, with internal exception handling being responsible for resolving scripting code problems raised by errors, and external exception handling for providing feedback to the user or logging exception information.

  Ix. Conclusion

This article discusses in detail a very important feature of the JavaScript language, "Exception handling", which Web developers should have a good grasp of and be flexible in practical applications so that HTML pages that contain scripting code are truly not exceptional and considerate.



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.