Exceptions: When Things Go Wrong
10.2 Handling Exceptional Conditions
Java’s Default Exception Handling
To help detect and handle common runtime errors, Java’s creators incorporated an exception-handling model into the language itself. In the case
of our divide-by-zero error, the Java Virtual Machine (JVM) would detect
the error and abort the program. To see this, consider the program in Figure 10.3. Note that the avgFirstN() method is passed an argument of
0 in the CalcAvgTest.main(). When the JVM detects the error, it will
abort the program and print the following message:
The error message describes the error and provides a trace of the method
calls, from last to first, that led to the error. This trace shows that the error
occurred in the CalcAverage.avgFirstN() method, which was called
by the CalcAvgTest.main() method.
As this example suggests, Java’s default exception handling is able to
detect and handle certain kinds of errors and exceptional conditions. In
the next section, we will identify what kinds of conditions are handled by
the JVM.