Inheritance Authoring an ActionScript 2.0 Subclass Interfaces Packages Exceptions
Unit IV
Inheritance
Authoring an ActionScript 2.0 Subclass
Interfaces Interfaces
Packages
Exceptions Exceptions
I N H E R I T A N C E
A Primer on Inheritance
Subclasses as Subtypes
An OOP Chat Example
Overriding Methods and Properties Properties
Constructor Functions in Subclasses
Subclassing Built-in Classes
Augmenting Built-in Classes & Objects
The Theory of Inheritance
Abstract and Final Classes Not Supported
Abstract and Final Classes Not Supported
A Primer on Inheritance
In OOP, inheritance is a formal
relationship between two
or more classes , wherein one class borrows (or inherits)
the property and method definitions of another class the property and method definitions of another class class A { public var p:Number = 10; public function x ( ):Void { public function x ( ):Void {trace("Method x( ) was called."); }}
We can create an instance of class
A, invoke method x( ),
and access property p like this:
var aInstance:A = new A( ); aInstance.x( ); // Displays: Method x( ) called. I t ( ) // Di l M th d ( ) ll d trace(aInstance.p); // Displays: 10
Now let s add a second class, Now let's add a second class
B, that inherits method x( ) B that inherits method x( )
and property p from class A.
A Primer on Inheritance (Contd…)
To set up the inheritance relationship between A and B , we use the extends keyword to indicate that class B inherits class class A s method and property definitions: A's method and property definitions:
class B extends A { }
Because class Because class B extends (inherits from) class A, B extends (inherits from) class A, instances of instances of
B can automatically use the method x( ) and the property p
var bInstance:B = new B( ); bInstance.x( ); // Displays: Method x( ) was called. trace(bInstance.p); // Displays: 10
class l B would define its B ld d fi it own methods and/or properties th d d/ ti in i addition to inheriting A's methods and properties.
class B extends A {{ public function y ( ):Void {trace("Method y( ) was called."); } }
A Primer on Inheritance (Contd…)
N i t f B ll th th d d ti f
Now instances of B can use all the methods and properties of both B and its superclass, A:
var bInstance:B = new B( ); var bInstance:B new B( ); // Invoke inherited method, defined by class A. bInstance.x( ); // Displays: Method x( ) was called. // Invoke method defined by class B. bInstance.y( ); // Displays: Method y( ) was called. // Access inherited property. trace(bInstance.p); // Displays: 10
Inheritance relationship bet een t o classes the e tended
Inheritance relationship between two classes, the extended class (in our case, class
A) is called the base class , and the
class that does the extending (in our case, class
B) is called the derived class.
A Primer on Inheritance (Contd…) A Primer on Inheritance (Contd )
However, the terms "base class" and "derived class" have several synonyms including several synonyms, including superclass and subclass, parent superclass and subclass parent
and child, and type and subtype.
third class,C, that extends class B
The following code shows and also defines a new method, z( ).
Class C can use all the methods and properties defined by
itself, its itself its superclass (B), or its superclass s superclass (A) superclass (B) or its superclass's superclass (A)
Every class in ActionScript ( )
both built-in and custom
inherits directly or indirectly from the root of the built-in hierarchy: Object.
Object class
The defines some very basic methods that all
classes can use. classes can use
A Primer on Inheritance (Contd…)
class C extends B { public function z ( ):Void { trace("Method z( ) was called."); } } var cInstance:C = new C( ); cInstance.x( ); // Displays: Method x( ) was called. cInstance x( ); // Displays: Method x( ) was called cInstance.y( ); // Displays: Method y( ) was called. cInstance.z( ); // Displays: Method z( ) was called. cInstance z( ); // Displays: Method z( ) was called trace(cInstance.p); // Displays: 10
class D inherits directly from class A. Class D uses the methods y A. and properties defined by itself and by its superclass,
class D extends A { public function w ( ):Void { bli f ti ( ) V id {
Subclasses as Subtypes yp
A subclass is considered a of its superclass. An
subtype
instance of the subtype can be used anywhere its
superclass s type is expected. superclass's type is expected var aInstance:A; var aInstance:A;
we can legally assign that variable an instance of any subclass of class
A: aInstance = new B( );
The preceding assignment works because the compiler
any instance of class B has (through inheritance)
knows that
all the methods and properties defined by class A. all the methods and properties defined by class A
However, the reverse is not true . We cannot assign an instance of A to a variable whose datatype is B: yp
var bInstance:B = new A( ); // Type Mismatch Error .
That assignment does not work because the compiler
cannot guarantee that an instance of class A will have the t t th t i t f l A ill h th
An OOP Chat Example
Consider a chat application that defines a class, ChatRoom, which handles communication among a group of users.
ChatRoom class defines methods for displaying & sending Ch tR l d fi th d f di l i & di chat messages and for managing a list of users in the room
AvatarChatRoom class's methods & properties
Example An inheritance example using ChatRoom and AvatarChatRoom class ChatRoom { private var userList:mx.controls.List; private var userList:mx controls List; public function displayMessage(userID:String, msg:String):Void { trace("Displaying chat message in chat text field."); } public function sendMessage(msg:String):Void { trace("Sending chat message."); } public function onAddUser(userID:String):Void { public function onAddUser(userID:String):Void { trace("Adding user to userList."); } public function onRemoveUser(userID:String):Void { trace("Removing user from userList."); }
public function onUserChangeName(userID:String, newName:String):Void {
trace( Changing name in userList. ); trace("Changing name in userList."); } }Example An inheritance example using ChatRoom and AvatarChatRoom
Constructor Function in Subclasses
A constructor function initializes the instances of a class by:
Calling methods that perform setup tasks
Setting properties on the object being created
When a class is extended, the subclass can define a constructor function of its own. A subclass constructor is constructor function of its own A subclass constructor is expected to:
Perform setup tasks related to the subclass p
Set properties defined by the subclass
Invoke the superclass constructor (superconstructor)
In all inheritance relationships, setup and property
relating to the superclass occur in the superclass
initialization
constructor, not in the subclass constructor. constructor not in the subclass constructor
Constructor Function in Subclasses (Contd..) ( )
A subclass constructor function, if specified, is formally required to invoke its superclass constructor , via the keyword
super , as the first statement in the function. th fi t t t t i th f ti class A { public function A ( ) { } } class B extends A { public function B ( ) { class B extends A { public function B ( ) {
// Invoke superclass's constructor function explicitly super( ); }} p ( ); }} public function B ( ) { // Invoke superclass's constructor function explicitly. super( );} public function B ( ) { bli f i B ( ) {
The Theory of Inheritance
Inheritance lets us from
separate a core feature set
customized versions of that feature set. Code for the core is
stored in a superclass while code for the customizations is kept neatly in a subclass.
More than one s bclass can e tend the s perclass More than one subclass can extend the superclass, allowing allo ing
multiple customized versions of a particular feature set to exist
simultaneously. architecture
Inheritance also lets us express the of an application in hierarchical terms that mirror the real world and the human psyche. the human psyche
to code reuse and logical
In addition hierarchy, inheritance
subtypes to be used where a single
allows instances of different
type is expected . Known as polymorphism
Polymorphism and Dynamic Binding
The word itself means literally
polymorphism "many forms "— each single object can be treated as an instance of its own class or as an instance of any of its superclasses its own class or as an instance of any of its superclasses .
Polymorphism's partner is dynamic binding , which guarantees that a method invoked on an object will trigger
the behavior defined by that object's actual class.
static type
Dynamic binding, which occurs at runtime , with
checking, which occurs at compile time checking which occurs at compile time
Dynamic binding is the runtime process by which each
invocation of draw( ) is associated with the appropriate ( ) pp p implementation of that method.
Dynamic binding is often called late binding: the method call is is bound to a particular implementation late (i.e., at bound to a particular implementation "late" (i e at runtime).
Polymorphism and Dynamic Binding(Contd..)
class Shape { public function draw ( ):Void { // No implementation. } p } } } class Circle extends Shape { public function draw ( ):Void {
}} class Rectangle extends Shape { l R t l t d Sh { public function draw ( ):Void { }} }} class Triangle extends Shape { pub c u ct o d a public function draw ( ):Void { ( ) o d {
}}
Abstract and Final Classes Not Supported pp
An abstract class is any class that defines one or more
abstract methods—methods that have a signature and a g return type but no implementation
A class that wishes to extend an abstract class must implement implement ;
all of the superclass's abstract methods all of the s perclass's abstract methods otherwise, a compile-time error occurs.
ActionScript 2.0 p does not yet support abstract classes y pp or abstract methods. Instead we simply define a method with no code in its body
A A fi final method l th d i is a method that th d th t must not be implemented by t t b i l t d b a subclass.
prevent programmers
Final methods are used to
from creating subclasses that accidentally introduce problems into the behavior of a superclass
Extending ImageViewer's Capabilities Authoring an ActionScript 2.0 Subclass Extending ImageViewer s Capabilities
Reposition the view region, Resize the view region
In the ImageViewerDeluxe class, we'll add the next two items
I Vi D l l 'll dd h i
I h
ImageViewer class already implements the first five requirements, but it stops there.
The
Zoom (resize) the image within the view region ( ) g g
Pan (reposition) the image within the view region
The list of possible functional requirements for our
Display image load progress
Display a border around the image
Display a border around the image
Crop an image to a particular rectangular "view region"
Load an image , Display an image
ImageViewer class:
Reposition the view region Resize the view region
The ImageViewerDeluxe Skeleton
The bare bones of any subclass requires:
A class declaration that defines the inheritance relationship
A constructor that invokes the superclass constructor with the expected arguments the expected arguments class ImageViewerDeluxe extends ImageViewer { g g { public function ImageViewerDeluxe (target:MovieClip, depth:Number, x:Number, y:Number, w:Number, h:Number, b d Thi k N b b d C l N b ) { borderThickness:Number, borderColor:Number) { super(target, depth, x, y, w, h, borderThickness, borderColor); );
} }
To create the ImageViewerDeluxe.as class file using Flash MX Professional 2004, follow these steps:
1. Choose File → New.
2. In the New Document dialog box, on the General tab, for I th N D t di l b th G l t b f Type, choose ActionScript File.
3.
3. Click OK. The script editor launches with an empty file. Click OK. The script editor launches with an empty file.
4. Copy the code into the script editor: in the next slide.
5. Choose File → Save As.
6. In the Save As dialog box, specify ImageViewerDeluxe.as
as the filename (which is case sensitive), and save the file in the imageviewer folder that you created. the imageviewer folder that you created
7. Instances of the ImageViewerDeluxe class have all the
ImageViewer class's methods and can be used anywhere
ImageViewer instances are used.Adding setPosition( ) and setSize( ) Methods g ( ) ( )
- Changes the location of the viewer by assigning the (x, y) coordinates
setPosition( )
- – of the viewer's main container movie clip of the ie er's main container mo ie clip
- Changes the size of the viewer by re-creating the mask and border g
setSize( )
y g
- – over the image movie clip (i.e., by recropping the image)
public function setPosition (x:Number, y:Number):Void { container mc x = x; container mc y = y; container_mc._x = x; container_mc._y = y; } }
The setSize( ) method, which resizes the image viewer by recropping the image: pp g g
public function setSize (w:Number, h:Number):Void { createImageClipMask(w, h); createBorder(w, h);
container_mc.image_mc.setMask(container_mc.mask_mc); t i i tM k( t i k )
}The ImageViewerDeluxe class, final version
class ImageViewerDeluxe extends ImageViewer { public function ImageViewerDeluxe (target:MovieClip, depth:Number, x:Number, y:Number, w:Number, h:Number, d th N b N b N b N b h N b borderThickness:Number, borderColor:Number) { super(target, depth, x, y, w, h, borderThickness, super(target, depth, x, y, w, h, borderThickness, borderColor); } } public function setPosition (x:Number, y:Number):Void { container_mc._x = x; t i container_mc._y = y;
} public function setSize (w:Number, h:Number):Void { public function setSize (w:Number h:Number):Void { createImageClipMask(w, h); createBorder(w, h); container_mc.image_mc.setMask(container_mc.mask_mc);
}}
ImageViewerDeluxe class, final version (Contd..)
public function getImageWidth ( ):Number { bli f ti tI Width ( ) N b { return container_mc.image_mc._width; } public function getImageHeight ( ):Number { public function getImageHeight ( ):Number { return container_mc.image_mc._height; } pub c u ct o setS o public function setShowFullImage(show:Boolean):Void { u age(s o oo ea ) o d { showFullImage = show; } public function getShowFullImage( ):Boolean { return showFullImage; } public function scaleViewerToImage ( ):Void {
setSize(getImageWidth( ), getImageHeight( )); } setSi e(getImageWidth( ) getImageHeight( )) }
public function onLoadInit (target:MovieClip):Void { super.onLoadInit(target); super onLoadInit(target);if (showFullImage) { scaleViewerToImage( ); } } }
I N T E R F A C E S
The Case for Interfaces
An interface is an ActionScript 2.0 language construct used to define a new datatype , much as a class defines a datatype.
A class both defines a A class both defines a datatype and provides the datatype and provides the for it, an interface defines a datatype in
implementation abstract terms only; an interface provides no implementation for the datatype. i l i f h d
An interface, instead of providing its own implementation, is that agree to provide the that agree to provide the
adopted by one or more classes adopted by one or more classes implementation.
A class that provides an implementation for an interface belongs both to its own datatype and to the datatype defined
The Case for Interfaces (Contd..)
class OrderListener { public function onOrderError ( ):Void { // Generic implementation of onOrderError( ) not sho n }} // Generic implementation of onOrderError( ), not shown… }} class StatsTracker extends OrderListener {
// Override OrderListener.onOrderError( ). public function onOrderError ( ) { // Send problem report to database. Code not shown… }} class OrderProcessor { class OrderProcessor { public function addListener (ol:OrderListener):Boolean {
// Code here should register ol to receive OrderProcessor events events, // and return a Boolean value indicating whether registration }} class OrderUI extends MovieClip { bli f i O d E ( ) { public function onOrderError ( ) {
// Display problem report on screen, not shown… }}
Interfaces and Multidatatype Classes yp
An interface is simply a list of methods. interface OrderListener { i t f O d Li t { function onOrderError( ); }}
implements keyword to enter into an agreement
Classes use the with an interface, promising to define the methods it contains.
class OrderUI extends MovieClip implements OrderListener {
public function onOrderError ( ) { // Display problem report on screen, not shown... }} }}Interface Syntax and Use
To create an interface in ActionScript 2.0, we use the interface keyword, using the following syntax:
interface SomeName {
function method1 (param1 :datatype ,...paramn :datatype ):returnType ;
function method2 (param1 :datatype ,...paramn :datatype ):returnType ; ...function methodn (param1 :datatype ,...paramn :datatype ):returnType ; u ct o et od (pa a datatype , pa a datatype ) etu ype ;
}
In interfaces, method declarations do not (and must not) include curly braces. i l d l b
public
All methods declared in an interface must be ; hence, by
public (which is the default) is omitted public (which is the default) is omitted
convention, the attribute convention, the attribute from method definitions in an interface.
Interface Syntax and Use (Contd..) y ( )
Class files
Contain the method and property definitions for each class. They start with the class keyword.
Intrinsic files
Contain method signatures strictly for the purpose of Contain method signatures strictly for the purpose of satisfying the compiler's type checking. They start with the
intrinsic keyword.
Interface files
Contain a list of methods to be implemented but not the implementations themselves. They start with the i l t ti th l Th t t ith th i t f interface keyword.
A class that wishes to adopt an interface's datatype p yp must agree to implement that interface's methods.
Interface Syntax and Use (Contd..) y ( )
The class uses the implements keyword, which has the following syntax:
class SomeName implements SomeInterface { }
The implementing class's method definitions must match the interface's method definitions exactly, including number of interface's method definitions exactly including number of parameters, parameter types, and return type.
If differs between the interface and the implementing class, p g , the compiler generates an error.
A class can legally implement more than one interface by separating interface names with commas, as follows: ti i t f ith f ll
class SomeName implements SomeInterface, SomeOtherInterface { SomeOtherInterface { }
P A C K A G E S
Larger applications, creates dozens of different L li ti t d f diff t classes and packages grouping them logically together. g
To group classes and interfaces together, we
use packages. namespace collision or namespace collision or naming conflict naming conflict .
A package is a unique place to put a group of classes, much as a directory on your hard drive , y y to put a group of files. is a unique place
Packages allow multiple classes of the same name to to
, coexist without namespace collisions coexist without namespace collisions because each package constitutes a namespace within which the class name is unique.
A namespace is a set of names that contains A i t f th t t i no
Package Syntax g y
The Domain Name System (DNS) defines a namespace in
reserve a domain nam
which registrants can e, such as moock.org g
describes the classes it
Every package has a name that contains.
By convention, package names By convention, package names but but
do not use initial caps do not use initial caps might use mixed case, such as greatUtils.
To refer to a specific class within a package, we use the dot operator: p
packagename.ClassName
game.Player Packages can be nested to form a hierarchy; that is, a package can contain another package. that is, a package can contain another package.
game.vehicles.SpaceShip
By nesting packages, we can organize our classes into discrete subcategories within a larger category, which again discrete subcategories within a larger category which again prevents naming conflicts.
Import statement p
An unqualified reference includes just the class name. var ship:SpaceShip = new SpaceShip( );
If a class is in a package, we must use a fully qualified reference when creating instances of the class and g specifying the datatypes of variables, parameters, and return types.
var ship:game.vehicles.SpaceShip = new game.vehicles.SpaceShip( );// Fully qualified hi l S Shi ( ) // F ll lifi d
The import statement lets us use an unqualified class reference as an f alias li f for a fully qualified class reference. f ll lifi d l f The basic syntax of import is:
import packagename.ClassName; import game.vehicles.SpaceShip;
Importing an Entire Package Importing an Entire Package
To import all the classes in a package, use the wildcard character, *:
import packagename.*;
This wildcard syntax lets us refer to any class in
p packagename by its unqualified name rather than its fully g y q
y qualified name.
import geometry.Circle; import geometry.Triangle; p g y g ; import geometry.Rectangle; import geometry. ; import geometry *;
If we use package wildcards to import two classes with the
same name but from different packages same name but from different packages , we again encounter we again encounter a namespace collision .
Package Naming Conventions
import game.vehicles.*; import ordering.*; var s:Ship = new Ship( ); // new game.vehicles.Ship Shi Shi ( ) // hi l Shi var s:ordering.Ship = new ordering.Ship( );
To avoid confusion, we should use fully qualified names for Ship. all references to
Just as two class names can conflict, two package names can , p g conflict.
To avoid package or class naming conflicts you should use the convention of
p placing all your classes and packages in a g y p g
package named after your organization's domain name.
com.acme com precedes acme (the package name is the reverse of the domain name).
Defining Packages
two
Defining a package for a class requires general steps:
Create a directory structure whose name identically
matches the package hierarchy. matches the package hierarchy
Specify the package name when defining the class.
There is no such thing as a package file. A package is a concept based on placing a given class s .as file in the concept based on placing a given class's as file in the appropriate folder.
To place the class Player in package com.yourdomain.game
Create a new directory named com. Create a new directory named com Create a new directory inside com named yourdomain.
Create a new directory inside yourdomain named game. Create a text file, Player.as, in the directory /com/yourdomain/game/.
In Player.as, class com.yourdomain.game.Player { // Class body not shown... }
Package Access and the Classpath
the root
In order for a .fla file to access a class in a package,
directory of the package must reside within the classpath.
The classpath is simply the The classpath is simply the list of directories (paths) list of directories (paths) on on your hard drive in which the compiler looks for classes.
Entries in the classpath can be added globally for all documents (the documents (the global classpath ) global classpath )
The global classpath includes the following directories:
The current directory, usually represented by a period ( ( )—i e the directory in which the fla resides .) i.e., the directory in which the .fla resides
The Classes directory, $(LocalData)/Classes—
Select Edit -> Preferences -> ActionScript -> Language - >ActionScript 2 0 Settings >ActionScript 2.0 Settings.
Under Classpath, click the plus sign (+) to add a new classpath entry. A blank entry appears.
In the classpath entry, type In the classpath entry type C:\data\actionscript\. (Or use C:\data\actionscript\ (Or use the crosshair button to browse to that directory.)
E X C E P T I O N S The Exception-Handling Cycle
we can write code that generates standardized errors t t d di d via the throw statement.
We handle those errors via the We handle those errors via the statement.
try/catch/finally
To generate an exception (i.e., signal an error) in our code, i l ) i d
throw expression
The The Error Error class, introduced as class introduced as a built-in class in Flash Player is a standard class for representing error conditions .
The Exception Handling Cycle (Contd..) The Exception-Handling Cycle (Contd..)
The Error class defines two
public properties, name and public properties name and message , used to describe the
error.
When the statement
throw
executes, program control is immediately y transferred to a
special section of code that
knows how to deal with the problem. problem
The code that deals with the problem is said to handle the
exception.
The Exception-Handling Cycle (Contd..) p g y ( )
The The block handles exceptions generated by the block handles exceptions generated by the try try
catch catch block.
The code in the catch block executes if, and only if, code in
try block generates an exception
the
The Exception-Handling Cycle (Contd..) p g y ( )
The keyword tells the
try
interpreter that we re about interpreter that we're about to execute some code that might generate an exception.
The catch block handles
exceptions generated exceptions generated by the by the try block.
The code in the catch block executes if, and only if, code in the try block generates an exception. exception.
The Exception-Handling Cycle (Contd..)
Code in a try clause
invokes a function that might throw an exception.
Code in the invoked Code in the in oked function throws an exception using the throw statement if an error occurs.
The The catch block catch block deals deals
with any errors that occur try block.
in the
The Exception-Handling Cycle (Contd..) p g y ( )
Control returns either to the try block or the catch block
When the When the catch block is executed, catch block is executed it receives the expression it receives the expression of the throw statement as a parameter .
Within a try block, if a statement executes, you can safely
trust that all preceding statements have executed successfully.
try block (or a method invoked in the try block) try block (or a method invoked in the try block)
If code in a If code in a throws an error, the remaining statements in the try block are
skipped and the statements in the catch block are executed .
the try block completes and
If no exception is thrown,
execution resumes with the statements immediately following the try/catch/finally statement. the try/catch/finally statement.
Handling Multiple Types of Exceptions
Each try block can have any number of supporting catch blocks.
When an exception is thrown in a Wh ti i th i t try block that bl k th t has multiple h lti l
catch block whose catch blocks , the interpreter executes the parameter's datatype matches the datatype of the value originally thrown.
catch
The datatypes of the parameter and thrown value are
catch catch
considered a considered a match if they are identical match if they are identical or if the or if the parameter type is a superclass of the thrown value's type.
The syntax of a y try statement with multiple catch blocks: y p
try { // Code that might generate an exception. } catch (e:ErrorType1) { // Error-handling code for ErrorType1.} catch (e:ErrorType2) { // Error-handling code for ErrorType2.} t h ( E T 2) { // E h dli d f E T 2 }
Handling Multiple Types of Exceptions (Contd..)
Exception Bubbling
The exceptions in a try block can be
thrown either directly or as the result of a method call .
An exception can be thrown anywhere in an ActionScript program, even on a frame in a timeline.
if no catch block exists? if no catch block exists? These mysteries are resolved These mysteries are resolved through the magic of exception bubbling .
throw statement executes, the interpreter immediately
When a , p y stops normal program flow and looks for an enclosing try block .
throw new Error("Something went wrong");
If the throw statement is enclosed in a try block, the interpreter next tries to find a catch block whose parameter's datatype
matches atc es t e datatype o t e a ue t o the datatype of the value thrown
try { throw new Error("Something went wrong"); }
Exception Bubbling (Contd…)
If a matching catch block is found If t hi t h bl k i f d , the interpreter transfers th i t t t f
program control to that block:
try { throw new Error( Something went wrong ); try { throw new Error("Something went wrong");
} catch (e:Error) { //Handle problems… } But if a matching catch block cannot be found or if the throw
try block in the first place,
statement did not appear within a
then the interpreter checks whether the throw statement
occurred within a method or function. occurred within a method or function public function doSomething ( ):Void { throw new Error("Something went wrong"); } ( g g ) } class ErrorDemo { public function doSomething ( ):Void { trace("About to throw an exception from doSomething( ) "); throw new Error("Something went wrong"); }
8
4
Uncaught Exceptions
If the interpreter never finds a catch block that can handle the thrown exception
Sends the value of the thrown Error object's message property to the Output panel
Aborts execution of all code currently remaining in the call Aborts execution of all code currently remaining in the call stack
class ErrorDemo { public function doSomething ( ):Void { throw new Error("Something went wrong"); } public static function startApp ( ):Void { doSomething( ); }} ErrorDemo.startApp( ); ErrorDemo startApp( );
The finally Block
A try block contains code that might throw an exception, and a catch block executes code in response to a thrown exception.
Th fi ll bl k b i l t h th
The finally block, by comparison, always executes, whether or not code in the
try block throws an exception.
The finally block is placed once (and only once) as the last The finally block is placed once (and only once) as the last block in a try/catch/finally statement.
try { // Statements } catch (e:ErrorType1) { // Handle ErrorType1 exceptions. } t h ( E T ) { // H dl E T ti } catch (e:ErrorTypen) { // Handle ErrorTypen exceptions. } finally {// code always executes, how the try block exits. }} Misplacing the finally block causes a compile-time error.
The finally block executes in one of the 4 circumstances
Immediately after the try block completes without errors
Immediately after a catch block handles an exception
generated in the try block t d i th t bl k
Immediately
before an uncaught exception bubbles up
Immediately before a Immediately before a return, continue, or break statement return continue or break statement
transfers control try or catch blocks
out of the
The finally block of a try/catch/finally statement typically
contains cleanup code that must execute whether or not
an exception occurs in the corresponding try block.Limitations of Exception Handling in Limitations of Exception Handling in ActionScript 2.0
No Checked Exceptions No Checked Exceptions
In ActionScript 2.0, if a method throws an exception, it's up to the programmer to know about it in advance and handle it appropriately.
The compiler will make no complaints if an exception is not handled. not handled
No Built-in Exceptions
Flash doesn't throw an exception when a developer p p attempts an illegal operation, such as dividing by zero.
Neither the class library built into the Flash Player nor the Flash MX 2004 v2 components throw exceptions. Flash MX 2004 v2 components throw exceptions
Exception Performance Issues
The only exceptions generated in Flash are those thrown by custom-written programs.
First, Flash must relay all error information to the programmer Fi t Fl h t l ll i f ti t th using unwieldy error codes or return values .
Second Flash often Second Flash often fails silently when a runtime error occurs fails silently when a runtime error occurs . .
Exception Performance Issues
If a method or function encounters an error, it returns a
message or code describing the problem and expects the caller to know how to interpret that code
Both Both exception handling and error codes exception handling and error codes are useful and can be are useful and can be used together in different parts of the same program , depending upon the performance needs of different parts of your code. d
5
4 test benchmark g
test 5 5