The Artima Developer Community
Sponsored Link

caveat to defining specific exceptions



This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


caveat to defining specific exceptions

Posted by Jeff Wright on 17 Jun 1998, 8:54 PM

In general, I agree with the advice to throw meaningful,
specific subclasses of Exception. However, it's important to
consider how to do this in a way that allows the code to
evolve over time without breaking clients. As emphasized in the
article, the throws clause is an important part of the contract
between a class and its clients. If a future version of the
class needs to throw a new type of exception, the clients will
have to be recompiled.

A nice solution is used in package Many methods of
classes in this package throw IOException, which is actually
the superclass of numerous exception types. Most clients only
need to catch the more general IOException, but can handle
specific exceptions if needed. Future versions of these classes
may throw new subclasses of IOException without requiring client
code recompilation.

Another approach is to use an instance variable in the exception
class to indicate a subtype. This approach is useful for
exceptions thrown by CORBA services, since CORBA IDL does not
support an inheritance hierarchy for exceptions.



Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us