Java Reference
In-Depth Information
return atBatsNeeded;
}
...
}
The important part is that the class that defines this kind of object extends the basic class
java.lang.Exception
, which in turn extends the class
java.lang.Throwable
. We declare a
serialVersionUID
because the basic class of
Throwable
implements the
Serializable
in-
terface, and all good classes that extend that interface will declare a
serialVersionUID
(this
ation about the context in which the exception object was thrown. For example, a full stack
trace is contained in that object, allowing the receiver of the object to find out the state of the
virtual machine when the exception was thrown. This can be an immensely valuable piece of
information when debugging, since it will give you the call history that led to the exception
being thrown.
The receiver of an object that is returned from a
throw
is, naturally enough, a
catch
clause.
In the method that called the
getAverage()
method, the call needs to be wrapped in a
try
clause that contains a
catch
of the exception. An example of this is code that looks something
like:
BatterImpl someBatter;
float avg;
...
try{
...
avg = someBatter.getAverage();
...
} catch (NotEnoughAtBatsException e){
avg = 0;
printf(e.getNeeded() +
"more at bats needed for meaningful average\n");
}
In this code, the call to the
getAverage()
method occurs with a
try
block. Such a block
is followed by a series of
catch
clauses, each of which catches an
Exception
of a declared
type. The catch of the
NotEnoughAtBatsException
indicates the place where processing in
the calling function will resume if
getAverage()
throws the exception, and the variable
e