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
Where should we define exceptions?
Posted by Bill Venners on 24 Jun 1998, 2:02 PM
> I was very excited to see your article about exceptions on the
> JavaWorld site. I have been putting together a coding standard.
> As with most other I have come across on my web searches, mine
> is primarily based on JavaSoft's standards. No where have I
> seen a good standard dealing with exceptions. The problem I
> see is that on large projects most exceptions that developers
> define are fairly simple with two constructors, one that takes
> no args and on that takes a String. Say I have a project has
> two packages that a totally seperate from each other but both
> do some sort of parsing. I think most developers would tend
> to unknowingly define a ParseException in both packages which
> leads to confusion and does not promote code reuse. I was
> thinking that it might be a good idea to create an exception
> package where all exceptions are defined. Then when a developer
> needs to define a new exception he first looks in this package
> to see if there is anything he can use and then if not defines
> one there. The downfall of this approach is that instead of
> just being able to deliver one package if you also have to
> deliver this backage package with several exceptions that your
> package doesn't need. What are your thoughts? Have you seen
> any good standards?
My thought on this is that code reuse probably isn't that
critical when all you are doing is creating a class that only
has two constructors and no methods.
One other reader submitted a comment saying that they thought
inner classes were a convenient place to define exception types.
In this way, the exception class is defined in the same class
as the class that throws the exception. The trouble here is
that two classes in the same package might even declare the
same exception, and then the client would have to say
Class1.ParseException and Class2.ParseException. Of course, I
just said code reuse isn't that big of a deal, but the
extra typing and potential confusion might be a more
I think my own feeling is that I would tend towards the
approach that seems to be taken by the Java API. Exceptions
that will be thrown by classes in each package are defined
in that package (as top-level, unnested (not inner) classes).
So within a certain package, there will be just one
ParseException. But across two packages there might be two
ParseExceptions. I agree that having two different
ParseExceptions could cause confusion, so this approach isn't
I'd be interested in hearing other people's opinions on this
one. It might also make a good opinion survey for JavaWorld.