
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
262
|
Chapter 10: Exceptions
throw new BoxUnderZeroException( );
} else if (w > Number.MAX_VALUE) {
throw new BoxOverflowException( );
}
width = w;
}
Notice that we do not pass any error description to the various Box exception con-
structors. Once again, the description of each exception is set by each custom Error
subclass using its
message property.
With each Box exception represented by its own class, the errors that can be gener-
ated by the setWidth( ) method are well-known to programmers working with Box
instances. The exception types are visible outside the Box class, exposed appropri-
ately to programmers working on the application. Just by glancing at the application
class hierarchy, the programmer can determine the exceptions that relate to the Box
class. Furthermore, if the programmer mistakenly uses the wrong name for an excep-
tion, the compiler generates a datatype error.
Now let’s see how to add branching logic to our code based on the types of excep-
tions that can be generated by Box.setWidth( ). Pay close attention to the datatype of
each catch block parameter:
var b:Box = new Box( );
var someWidth:Number = -10;
try {
b.setWidth(someWidth);
} catch (e:BoxOverflowException) {
// Handle overflow.
trace("An error occurred: " + e.message);
trace("Please specify a smaller value."); ...