Java Reference
In-Depth Information
} catch (SomeException e) {
e.printStackTrace();
System.exit(1);
}
Although somewhat better, this still misses the point. It is possible that the only thing you can
do in the face of an exception is to print out the state of the world when the exception occurs
and shut things down. But generally you can do more than that. If nothing else, there is a fair
amount of cleaning up that should be done before exiting. In most specific cases, there is ac-
tually something that you can do to recover from the exceptional condition and continue with
the program. All it needs is a little thought, and writing the right exception handler.
The Dark Side
What has been said thus far is true of all exceptions in the Java language. Almost. But there is
an exception type that, although it is needed, can also lead to a perversion of all that is good
about the Java exception system.
When the exception system was first being designed, there was worry about exceptional con-
ditions that could occur because of problems with the machine on which the program was be-
ing run, bugs in the virtual machine, or a security violation. These sorts of things can happen
at any time. But it would only clutter up the language to require that every method declare
that it could throw an exception for these reasons. For one thing, it generally wouldn't be the
method that throws such an exception (it would be the underlying virtual machine); for anoth-
er, it would just make the code longer, not more robust.
To deal with this, a special sort of exception, the RuntimeException , was built into the Java
environment. A RuntimeException can be thrown at any time, and does not need to be de-
clared as part of the signature of a method. Further, since it can be thrown at any time, the
code that might receive a thrown RuntimeException does not have to have a catch clause
for those exceptions (otherwise, all code would need to be wrapped in a try block). This is
not only for the sake of expediency, but also because there is really nothing that the applic-
ation program can do to deal with the kinds of situations that are meant to be signaled by
a RuntimeException . When one of these is thrown, the thinking went, things are so out of
whack that the best thing that can happen is for the program to fall into a pile of constituent
bits.
Search WWH ::




Custom Search