Try... catch... finally statement

Source: Internet
Author: User
Tags finally block

Try {//... Try block...} Finally {//... Finally block...}
Try {//... Try block...}
Catch (Error[: Errortype1])//... Catch Block...}
[Catch (Error[: Errortypen]) {//... Catch Block...}]
[Finally {//... Finally block...}]

Contains a code block. If an error occurs in the code block, the error is returned. IftryAny code in the code block throws an error (usingthrowStatement), the control will be passedcatchBlock (if any), and then passfinallyCode block (if any ). Whether an error is thrown or not,finallyThe code block will always be executed. IftryThe code in the code block does not throw an error (that is, iftryCode block is successfully completed ),finallyThe code in the code block is still executed. Even iftryCode block usagereturnStatement exit,finallyThe code block will still be executed.

tryThe code block must be followed bycatchCode block,finallyCode block, or both. OnetryMultiple code blockscatchCode block, but only onefinallyCode block. You can nest any layertryCode block.

catchTheErrorThe parameter must be a simple identifier, suche,theExceptionOrx. You can alsocatchThe variable in the processing function specifies the type. When there are multiplecatchWhen a code block is used together, you can capture errors of the type fromtryMultiple types of errors thrown in the code block.

If the thrown exception is an object, the type will match when the thrown object is a subclass of the specified type. If the thrown error belongs to a specific typecatchThe code block is executed. If the thrown exception does not belong to the specified typecatchCode block, but the exception is automatically removed fromtryThe code block is thrown and thrown to the matchedcatchProcessing functions.

If an error is thrown in a function and the function does not containcatchProcessing function, the ActionScript interpreter will exit the function and any caller function untilcatchCode block. In this processfinallyProcessing functions.

Availability:ActionScript 1.0; Flash Lite 2.0

Parameters

Error:Object -- fromthrowThe expression thrown by a statement, usually an error class or an instance of a subclass of it.

Example

The following example shows how to createtry..finallyStatement. BecausefinallyThe code in the code block is certainly executed. Therefore, it is usually used intryAfter the code block is executed, perform any necessary cleanup. In the following example,setInterval()Call the callback function every 1000 milliseconds (1 second. If an error occurs, an error is thrown.catchCode block capture. Whether an error occurs or not, the finally code block is executed. BecausesetInterval(), SoclearInterval()Must be placed infinallyBlock to ensure that the interval is cleared from memory.

myFunction = function () {  trace("this is myFunction"); }; try {  myInterval = setInterval(this, "myFunction", 1000);  throw new Error("my error"); } catch (myError:Error) {  trace("error caught: "+myError); } finally {  clearInterval(myInterval);  trace("error is cleared"); }

In the following example,finallyThe code block is used to delete an ActionScript object, regardless of whether an error occurs. Create a new as file named account..

class Account {  var balance:Number = 1000;  function getAccountInfo():Number {  return (Math.round(Math.random() * 10) % 2);  } }

In the directory where account. As is located, create a new as or FLA document and enter the following ActionScript in frame 1st of the timeline:

import Account; var account:Account = new Account();try {  var returnVal = account.getAccountInfo();  if (returnVal != 0) {  throw new Error("Error getting account information.");  } } finally {  if (account != null) {  delete account;  } }

The following exampletry..catchStatement. RuntryCode in the code block. IftryIf any code in the code block throws an exception, the control is passedcatchCode block.Error.toString()Method to display an error message in a text field.

In the directory where account. As is located, create a new FLA document and enter the following ActionScript in frame 1st of the timeline:

import Account; var account:Account = new Account(); try {  var returnVal = account.getAccountInfo();  if (returnVal != 0) {  throw new Error("Error getting account information.");  }  trace("success"); } catch (e) {  this.createTextField("status_txt", this.getNextHighestDepth(), 0, 0, 100, 22);  status_txt.autoSize = true;  status_txt.text = e.toString(); }

The following example illustratestryCode block, which contains multiple SPECIFIED TYPEScatchCode block. According to the error type,tryThe code block throws different types of objects. In this example,myRecordSetIs an instance of a class named recordset (assuming there is such a class ).sortRows()Methods can throw two types of errors: recordsetexception and malformedrecord.

In the following example, the recordsetexception and malformedrecord objects are subclasses of the error class. They are all defined in their own as class files.

// In recordsetexception. as: Class recordsetexception extends error {var message = "record set exception occurred. ";} // In malformedrecord. as: Class malformedrecord extends error {var message = "Malformed Record exception occurred. ";}

In the recordset classsortRows()Method. The following example shows the appearance of the Code:

class RecordSet {  function sortRows() {  var returnVal:Number = randomNum();  if (returnVal == 1) {  throw new RecordSetException();  }  else if (returnVal == 2) {  throw new MalformedRecord();  }  } function randomNum():Number {  return Math.round(Math.random() * 10) % 3;  }}

Finally, in another as file or FLA script, the following code callssortRows()Method. It targetssortRows()Each type of error thrown defines the correspondingcatchCode block

import RecordSet; var myRecordSet:RecordSet = new RecordSet();try {  myRecordSet.sortRows();  trace("everything is fine"); } catch (e:RecordSetException) {  trace(e.toString()); } catch (e:MalformedRecord) {  trace(e.toString()); }

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.