JS practice: Exception Handling try {} catch (e ){}

Source: Internet
Author: User

In program development, programmers often face how to write code to respond to the occurrence of error events, that is, exception handlers ). If the exception handling code is well-designed, the final presentation to the user will be a friendly interface. Otherwise, visitors will be surprised by the inexplicable phenomenon ".
1. What is exception handling?

When the JavaScript program is running, such as the array index out-of-bounds, Type mismatch, or syntax error, the JavaScript interpreter will cause exception processing. ECMAScript defines six types of errors. In addition, we can use the Error object and throw statement to create and trigger custom exception handling information.

Ii. Advantages of Exception Handling Technology

By using the exception handling technology, we can respond to error events in a structured manner, so that the exception handling code can be scientifically separated from Normal script code, in the end, we were able to focus on writing core programs that completed the main functions.

3. Use try... Catch... Finally executes Exception Handling

In JavaScript, we use try... Catch... The finally statement is used to execute Exception Processing, that is, to capture exceptions caused by errors or exceptions generated by executing throw statements. Its basic syntax is as follows:

Try {
// Exception statements may be generated here
} Catch (error ){
// Here is the statement for Exception Handling
} Finally {
// Here is the exit statement
}



In the above Code, the statements in the try block are first executed. If an error occurs during running, the control is transferred to the statement located in the catch block. The error parameter in the brackets is passed as the exception variable. Otherwise, the catch BLOCK statement is skipped and not executed. Whether the execution of the statements in the catch block is completed when an error occurs or the execution of the statements in the try block is not completed, the statements in the finally block are executed.

Here is an example:

<Script language = "javascript">
Try {
Document. writeln ("start to execute the try BLOCK statement ---> ")
Document. writeln ("no exceptions yet ---> ")
Alert (prompt ("enter a value :","")))
} Catch (err ){
Document. writeln ("catch exceptions and start to execute catch Block statements ---> ");
Document. writeln ("error name:" + err. name + "---> ");
Document. writeln ("error message:" + err. message + "---> ");
} Finally {
Document. writeln ("start to execute the finally BLOCK statement ")
}
</Script>



Input abc and confirm. The output result is as follows:

"Start to execute the try BLOCK statement ---> no exceptions yet ---> catch the exception and start to execute the catch Block statement ---> error name: TypeError ---> error message: 'abc' undefined ---> start to execute the finally BLOCK statement"

The preceding example starts with a try BLOCK statement. When the output information "no exceptions have occurred", the input dialog box is displayed, asking the user to enter a value. When the input information "abc" is invalid, an exception is thrown, so the statements in the remaining try block will be skipped and the catch BLOCK statement will be executed. The err parameter starting with the Catch block is the exception object. It has two attributes: name and message. Finally, execute the finally BLOCK statement.

As shown in the preceding figure, the catch BLOCK statement is skipped after the try BLOCK statement is executed. A window displays the input value and finally the finally BLOCK statement is executed.


4. try... catch... finally Deformation

Try... Catch... The finally statement has two types of deformation applications: try... Catch or try... Finally.

Try... The catch structure is the most common. Its Execution Process is: when no exception occurs, the try BLOCK statement is executed, or the catch Block statement is executed after the exception occurs, the control will be transferred to the entire try... The statement after the catch structure. See 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 ")



For try... In the finally structure, when exceptions occur, the finally BLOCK statement will not be executed because no BLOCK statement is caught to capture errors. Therefore, this structure is rare in practical applications.

V. Exception format: Error object

In JavaScript, exceptions occur as Error objects. The Error object has two attributes: The name attribute indicates the exception type, and the message attribute indicates the meaning of the exception. Based on the values of these attributes, we can decide how to handle exceptions, such:

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 expression of the content entered by the user and then displays it. If a SyntaxErroe type error occurs during the evaluation, the information of "Invalid expression" is displayed. Otherwise, the user obtains the information "Cannot uate ".

There are six Error. name values:

Error :() usage and definition are inconsistent
RangeError: value out of bounds
ReferenceError: an invalid or unrecognized reference value
SyntaxError: Syntax Parsing Error
TypeError: Incorrect operand type
URIError: The URI processing function is improperly used.




Vi. customized exception information

The above six types of errors basically cover the errors that may occur when the script is running. In addition to these types, we can use the Error constructor to customize the exception types. The syntax is as follows:
MyError = new Error (msg)



The msg parameter indicates the message attribute value of the new exception. At the same time, we can also create a new object type as a child type of Error:

Function MyError (msg ){
This. name = "MyError"
This. message = msg
}
MyError. prototype = new Error;



Then, we can create an instance of the custom error subclass:
MyError = new MyError ("My error message ")



VII. trigger exceptions

After creating an Error object, you can use the throw statement to trigger corresponding exceptions. The syntax of Throw is as follows:

Throw errObj

ErrObj must be an Error object or a child type of Error. When an exception is triggered in the try block code, the control is directly transferred to the catch Block.

The following code triggers an exception in the try block, sets the exception information to "oops", and transfers the control to the catch Block:

Var s
Try {
S = "one"
Throw new Error ("oops ")
S + = "two"
} Catch (err ){
S + = err. message
}
S + = "three"
Alert (s)


Writing code to trigger exceptions has many advantages, such as being conducive to custom error types, fast transfer to catch block execution, and the following section describes how to pass errors to the outer layer in nested exceptions.


8. nested Exception Handling

JavaScript supports multi-level nested exception handling. In general, we can capture and handle errors in the catch code block for internal exception handling, and then trigger the exception again, in this way, the catch code block for external exception handling can be further processed. Here is 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, beginner 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 output result 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 nested exception handling is that it enables us to handle errors in stages. Internal exception handling can solve the script code problems caused by errors, external Exception Processing is used to provide feedback to the user or to log the exception information.

IX. Conclusion

This article discusses in detail a very important feature of the JavaScript language, "Exception Handling". Web developers should master it well and handle it flexibly in practical applications, in this way, the HTML page containing script code is truly not exceptional and understandable.

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.