Turn JS Practice: Exception Handling Try{}catch (e) {}

Source: Internet
Author: User
Tags finally block

program development, programmers often have to face is how to write code to respond to the occurrence of error events, that is, 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 a real "accident" of inexplicable phenomenon.
I. What is exception handling

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

Ii. Advantages of exception handling technology

By using exception handling techniques, we can implement a structured approach to the occurrence of error events, separating exception handling code from normal scripting code science, and ultimately allowing us to focus on writing core programs that do the main functions.

Iii. using try...catch...finally to perform exception handling

In JavaScript, we use the Try...catch...finally statement to perform exception handling, which is used to catch exceptions caused by an error or to execute a throw statement. Its basic syntax is as follows:

try {
Here are the statements that may produce exceptions
} catch (Error) {
Here is the statement that is responsible for exception handling
} finally {
Here is the export statement
}



In the code above, 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 statements in the finally block are executed, whether the statement in the CATCH block is executed when an error occurs, or if the statement in the try block does not occur.

Let's look at an example:

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



We enter ABC and then confirm that the output is as follows:

"Start execution of the TRY block statement---> No exception has occurred---> Snap to exception, start execution of Catch block statement---> Error name: TypeError---> Error message: ' abc ' undefined---> Start execution finally Block Statement "

The above routine starts with a try block statement, and when the output message "No exception has occurred", the input dialog box pops up, asking the user to enter a numeric value, and when we enter the illegal information "ABC", an exception is thrown, so the statement in the remaining try block is skipped and the CATCH block statement starts executing. The Err argument at the beginning of the catch block acts as an error object with this exception, and it has a name and a message two properties. Finally, the statement that executes the finally block.

We see that, since no error occurred, when the statement of the try block is executed, the CATCH block statement is skipped, a window appears showing the value entered, and finally a finally block statement is executed.


Iv. Deformation of try...catch...finally

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

Try...catch This structure is most common, and its execution occurs when there is no exception after execution of a try block statement, or after an exception has been executed after the CATCH block statement, the control is transferred to the statement following the entire try...catch structure. Take a look at the following example:

try {
Document.writeln ("Beginnng the Try Block")
Document.writeln ("No Exceptions Yet")
Create a syntax error
("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, when an exception occurs, the statement of the final finally block is not executed because there is no catch block statement to catch the error. Therefore, this kind of structure is very rare in practical application.

V. Manifestations of exceptions: Error objects

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

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



The above code evaluates the content entered by the user and then displays it. If a Syntaxerroe type error occurs during the evaluation process, the user is presented with the message "Invalid expression", otherwise the user gets the message "Cannot Uate".

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

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




VI. Customization of exception information

The six error types above basically cover errors that might occur when the script is running. 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 new exception that is defined for the message property value. At the same time, we can create new object types as subtypes of 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

Once you have created 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 error. After 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 the control is transferred to the CATCH block:

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


There are many advantages to writing code to trigger exceptions, such as the benefit of custom error types, quick transfer to catch block execution, and the following to pass errors to the outer layer in nested exceptions.


Eight, nested exception handling

JavaScript supports multiple levels of nested exception handling. In general, we can catch and handle errors in the catch block of internal exception handling, and then trigger the exception again, so that further processing can be done further in the catch code block for external exception handling. Let's take a look at an example of 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 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 resulting output 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 benefit of nested exception handling is that we can handle errors in a very good way, with internal exception handling being responsible for solving the scripting code problems raised by errors, and external exception handling for providing feedback to the user or logging the exception.

Ix. Conclusion

This article discusses in detail a very important feature of the JavaScript language "exception handling", the web developer should be well mastered and flexible in practical applications, so that the HTML page containing script code is really no exception, understanding.

Turn JS Practice: Exception Handling Try{}catch (e) {}

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.