Using Chained Exceptions
It’s often suitable to
catch a particular type of exception and rethrow a different one.
This is sometimes necessary because a client might not know or care
to handle the original exception. For example, say that a client
invokes an action on a Struts application to upload an image file to
a database. Let’s further assume the
Action
class calls an update method whose
signature looks like the following:
public void updateImageFile( String imagePath ) throws UploadException;
When the method is called with an image to upload and a problem
occurs, an UploadException
will be thrown.
However, the underlying problem will be more specific—for
example, the filesystem is full or the database already has the
image, depending on the destination of the image upload. The original
exception thrown may be IOException
or
SQLException
, but the user
doesn’t need to know or care about this level of
detail; all he needs to know is that the update function failed.
Although the end user doesn’t care about the
specific exception thrown, the system administrator or the developers
who will be assigned the task of debugging and fixing the problem do.
That’s why you don’t want to throw
away the root cause of the problem when you rethrow a different
exception.
Prior to Version 1.4, Java didn’t provide a built-in mechanism to wrap the original exception with a new one. Developers were left to their own devices to solve the problem. Most homegrown solutions looked something like the ...
Get Programming Jakarta Struts now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.