Java Reference
In-Depth Information
If an
InputMismatchException
is generated by lines 25 or 27, the
try
block
termi-
nates
and execution
continues
with the
catch
block at lines 34-41. In this case, method
quotient
is not called. Then method
main
continues after the last
catch
block (line 48).
Exception handling is designed to process
synchronous errors
, which occur when a state-
ment executes. Common examples we'll see throughout the topic are
out-of-range array in-
dices
,
arithmetic overflow
(i.e., a value outside the representable range of values),
division by
zero
,
invalid method parameters
and
thread interruption
(as we'll see in Chapter 23). Excep-
tion handling is not designed to process problems associated with
asynchronous events
(e.g., disk I/O completions, network message arrivals, mouse clicks and keystrokes), which
occur in parallel with, and
independent of
, the program's flow of control.
Software Engineering Observation 11.2
Incorporate your exception-handling and error-recovery strategy into your system from the
inception of the design process—including these after a system has been implemented can
be difficult.
Software Engineering Observation 11.3
Exception handling provides a single, uniform technique for documenting, detecting and
recovering from errors. This helps programmers working on large projects understand each
other's error-processing code.
Software Engineering Observation 11.4
There's a great variety of situations that generate exceptions—some exceptions are easier
to recover from than others.
All Java exception classes inherit directly or indirectly from class
Exception
, forming an
inheritance hierarchy
. You can extend this hierarchy with your own exception classes.
Figure 11.4 shows a small portion of the inheritance hierarchy for class
Throwable
(a
subclass of
Object
), which is the superclass of class
Exception
. Only
Throwable
objects
can be used with the exception-handling mechanism. Class
Throwable
has two direct sub-
classes:
Exception
and
Error
. Class
Exception
and its subclasses—for instance,
Runtime-
Exception
(package
java.lang
) and
IOException
(package
java.io
)—represent
exceptional situations that can occur in a Java program and that can be caught by the
application. Class
Error
and its subclasses represent
abnormal situations
that happen in
the JVM. Most
Error
s happen infrequently and should not be caught by applications—it's
usually not possible for applications to recover from
Error
s.
The Java exception hierarchy contains hundreds of classes. Information about Java's
exception classes can be found throughout the Java API. You can view
Throwable
's docu-
mentation at
docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html
. From
there, you can look at this class's subclasses to get more information about Java's
Excep-
tion
s and
Error
s.