Java Reference
In-Depth Information
Chapter 3. Exceptions
Few features of the Java language are as generally reviled and misunderstood as Java excep-
tions. Exceptions have to be declared as part of the signature of a method, and if an exception
is declared as being thrown by a method, any code calling that method either needs to throw
that same exception or needs to occur within a try block, and the calling method must include
code that will catch the exception and deal with it. There are large numbers of programmers
who hate this “extra” work and think that it makes their code messy and hard to read. Worse
yet, they have to think about what could go wrong, and wrap their code calling anything that
could throw an exception in a block. These blocks are uninteresting, and make it hard to re-
member what it is that the method is trying to do in the first place.
But exceptions in the Java language are definitely part of the good things about the language.
Using exceptions correctly, your code can be easier to read. Using exceptions, your code can
be more reliable. Using exceptions, your code can be easier to maintain. Those who object to
the exception mechanism either don't understand it, don't realize what it can do, or are simply
lazy twits who don't care about writing reliable code. [ 10 ] In spite of evidence to the contrary, I
like to think that there are very few in the third category. So in this chapter we will talk about
exceptions for those in the first two groups, explaining how exceptions should be used and
why this sort of use makes them contributors to the good parts of the Java language.
The Basics
In Java, an Exception (and its evil, but necessary, twin the RuntimeException ) is a class that
extends the Throwable class. Anything that is an instance of a Throwable can be returned
from a method by using the throw statement, and these throw return values can be caught by
an exception handler in the calling method. All of which sounds complicated. An easier way
to think of this is that it is possible to have a set of alternate return values in any Java method,
as long as those return values are of the Throwable class (or any class that has Throwable as
an ancestor class). Not only can the method in which the exception occurs return an alternate
value, the calling method can indicate where processing will resume when such a value is re-
turned.
 
Search WWH ::




Custom Search