
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Nested Exceptions
|
271
Nested Exceptions
So far we’ve used only single-level try/catch/finally statements, but exception-handling
logic can also be nested. A try/catch/finally statement can appear inside the try, catch,
or finally block of another try/catch/finally statement. This hierarchical nesting allows
any block in a try/catch/finally statement to execute code that might, itself, throw an
error.
For example, suppose we were writing a multiuser, web-based message board sys-
tem. We define a core class for the application (called BulletinBoard), another class
that manages the user interface (called GUIManager), and another class that repre-
sents a user on the board (called User). We give BulletinBoard a method,
populateUserList( ), which displays the list of current active users. The
populateUserList( ) method splits its work into two stages: first it retrieves a List
component from the application’s GUIManager instance, then it populates that List
with users from a supplied array of User instances. These two stages can both poten-
tially generate an exception, so a nested try/catch/finally structure is used in the
populateUserList( ) method. Let’s take a closer look at this nested structure.
During the first stage of populateUserList( ), if the List component isn’t available, a