
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Handling Multiple Types of Exceptions
|
257
Determining Exception Type Granularity
Should you define an Error subclass for each error condition? Typically, no, you
won’t need that level of granularity because in many cases multiple error conditions
can be treated in the same way. If you don’t need to differentiate among multiple
error conditions, you can group them together under a single custom Error subclass.
For example, you might define a single Error subclass named InvalidInputException
to handle a wide range of input problems.
That said, you should define a separate Error subclass for each error condition that
you want to distinguish from other possible conditions. To help you understand
when you should create a new subclass for a given error condition and to demon-
strate how to group multiple conditions into a single subclass, let’s return to our
familiar Box class.
Earlier we generated three exceptions from the Box.setWidth( ) method: one for gen-
eral invalid data, one for too small a width, and one for too large a width. All three
Box-related exceptions used the generic Error class. Here’s the code again:
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 ...