
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Handling Multiple Types of Exceptions
|
255
Handling Multiple Types of Exceptions
Our first exception example was overly simplistic. What happens if our method gen-
erates more than one kind of error? Are they all sent to the same catch block? Well,
that’s up to the developer; they certainly could be, but it’s more typical and better
practice for different kinds of errors to be handled by separate catch blocks. Let’s
examine why.
Suppose we wanted a finer-grained set of error messages in our setWidth( ) method:
one for general invalid data, one for too small a width, and one for too large a width.
Our revised setWidth( ) method might look like this:
public function setWidth (w:Number):Void {
if (isNaN(w) || w == null) {
throw new Error("Illegal Box dimension specified.");
} else if (w <= 0) {
throw new Error("Box dimensions must be greater than 0.");
} else if (w > Number.MAX_VALUE) {
throw new Error("Box dimensions must be less than Number.MAX_VALUE.");
}
width = w;
}
To handle the three possible error messages in our new setWidth( ) message, we
might be tempted to code our try/catch/finally statement as follows:
try {
b.setWidth(someWidth);
// If we get this far, no exception occurred; proceed as planned.
trace("Width set successfully.");
} catch (e:Error) {
switch (e.message) {
case ...