But the ability to not declare or deal with a RuntimeException has led to a great temptation
among Java programmers. In the midst of writing the implementation of a method, a program-
mer discovers that there is an exceptional condition that he hadn't thought of in the original
design of the system. “Make it a subclass of RuntimeException ,” a small, inner voice says.
“That way you don't have to change your method declaration. All the code that calls your
method won't have to be changed to deal with a new catch clause. Come on, no one will no-
tice—the problem will hardly ever happen.”
This is the voice of the dark side calling to you. It is the first step down the path that leads to
unreliable systems. This is, not to put too fine a point on it, evil. It doesn't matter that others
before you have done this, even in standard Java libraries. Resist the evil, and don't declare a
new RuntimeException . It may be more work, but it is work that is there because it is needed.
Subverting the exception mechanism is like subverting the type system (which also happens).
It might make your current task easier, but it will only cause more work and heartache in the
future when you try to find out why your system is failing and what method is throwing the
exception that is causing everything to fall apart.
Of course, if you actually design your code to throw only subclasses of RuntimeException ,
then you have gone beyond simple evil. You have now become a corrupter of others, and
should feel the appropriate shame and be subject to the appropriate ridicule. And you wouldn't
want that, would you?
The one time that you will want to violate this principle is when you want to throw an excep-
tion that is already defined in the Java environment as a RuntimeException . For example,
you may decide that you are going to require that an actual object is passed into a method,
and that it is an error to pass in null instead. You could define your own Exception class
This exception seems to have just the right semantics for the situation in question, but it is a
RuntimeException . So you are stuck between a rock and a hard place. You either throw a
RuntimeException in your code, or define a new Exception class that is a duplicate of one
that is defined in the platform and is in common use.
I will admit that there was a time when I was something of an Exception absolutist, and ar-
gued for the creation of a duplicate class in this circumstance. But too much water has flowed
under (and, likely, over) that bridge. I still believe that the use of RuntimeException classes
is a bad thing, but sometimes one needs to bow to the reality of the environment.
So now, I think that in this case the lesser of the two evils is to use the existing exception. But
you should do everything in your power to warn users of your code that this exception might