JS Processing exception Try{}catch (e) {}

Source: Internet
Author: User
Tags finally block


Mxs&vincene─╄ovё: Today is very cruel, tomorrow is more brutal, the day after tomorrow is very good, but most people die in the evening, only those real heroes can see the sun after the day.

Mxs&vincene─╄ovё:we ' re Here's put a dent in the universe. Otherwise Why else even is here?

Text >>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>

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 when a JavaScript program occurs in a run such as an array index out of bounds, type mismatch, or syntax error, the JavaScript interpreter throws exception handling.  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.  The 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 is a statement that could produce an exception} catch (Error) {///Here is the statement responsible for exception handling} finally {//here is the exit statement} The statement in the try block is executed first in the code above. 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 take a look at an example: <script language= "JavaScript" > try {document.writeln ("Start executing a TRY block statement--->") Document.writeln ("Also     No exception 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 executing a TRY block statement---> No exception has occurred ---> Catch exception, start execution of Catch block statement---> Error name: TypeError---> Error message: ' abc ' undefined---> Start execution of Finally block statement "The above routine starts with a try block statement, when the output information" is not An 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.  Four, try...catch...finally deformation try...catch...finally statement has two kinds of deformation 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.  Consider 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 ("Ex    Ception caught, executing the CATCH block ")Document.writeln ("Error name:" + err.name) Document.writeln ("error message:" + err.message)} document.writeln ("Exe Cuting after the Try-catch statement ") if it is a try...finally structure, then when an exception occurs, the statement of the final finally block will not be executed 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 is in JavaScript, except that it appears 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 handle 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 code above will evaluate the content entered by the user and then display Come out.  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 types of Error.name, as follows: Error: () use inconsistent with definition Rangeerror: value out of bounds referenceerror: illegal or unrecognized reference value SyntaxError: Parsing error occurred TypeError: Operand type error urierror:uri handling function Improper use VI. Custom 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 by the message property value. At the same time, we can also create a new object type as a subtype 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 exception after creating 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, with the exception message set to "Oops", and then control 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) has many advantages in writing code to trigger exceptions, such as facilitating custom error types, quickly moving to catch block execution, and passing errors in nested exceptions as described below  to the outer layer. 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 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");  Generates 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 Caug HT, beginning inner catch block error Type:referenceerror error message:undefinedvariable is isn't defined executing in NER finally block Exception caught, beginning outer catch block Error type:referenceerROR error message:undefinedvariable is not defined executing outer finally block nested exception handling is the benefit of enabling us to handle errors in a well-phased manner, with internal exception handling to be responsible for  Resolves a scripting code problem that is caused by an error, and external exception handling 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 be well mastered and flexible in practical applications, so that the HTML page containing script code is really no exception, understanding.


JS Processing exception 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.