It is not a matter of IF but WHEN things will go wrong in a computer program. Sometimes there are bugs, errors of one form or another. There are also unforeseen use cases. You can never assume a computer program is perfect. Exception-Handling helps us to catch erroneous events and devise means of correcting them. We discuss this topic here since exception-handling can take more code than should be put into the main line of execution. In such cases, a method in an exception-handling class should be called. Exception handling mechanisms allow a program to continue executing, instead of terminating it abruptly, even if an error occurs in the program.
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.