Java Reference
In-Depth Information
Use throws
Know Java's built-in exceptions
Create custom exception classes
T his chapter discusses exception handling. An exception is an error that occurs at run
time. Using Java's exception handling subsystem you can, in a structured and controlled
manner, handle run-time errors. Although most modern programming languages offer some
form of exception handling, Java's support for it is both easy-to-use and flexible.
A principal advantage of exception handling is that it automates much of the error hand-
ling code that previously had to be entered “by hand” into any large program. For example,
in some older computer languages, error codes are returned when a method fails, and these
values must be checked manually, each time the method is called. This approach is both
tedious and error-prone. Exception handling streamlines error handling by allowing your
program to define a block of code, called an exception handler , that is executed automat-
ically when an error occurs. It is not necessary to manually check the success or failure of
each specific operation or method call. If an error occurs, it will be processed by the excep-
tion handler.
Another reason that exception handling is important is that Java defines standard excep-
tions for common program errors, such as divide-by-zero or file-not-found. To respond to
these errors, your program must watch for and handle these exceptions. Also, Java's API
library makes extensive use of exceptions.
In the final analysis, to be a successful Java programmer means that you are fully capable
of navigating Java's exception handling subsystem.
The Exception Hierarchy
In Java, all exceptions are represented by classes. All exception classes are derived from a
class called Throwable . Thus, when an exception occurs in a program, an object of some
type of exception class is generated. There are two direct subclasses of Throwable : Ex-
ception and Error . Exceptions of type Error are related to errors that occur in the Java
virtual machine itself, and not in your program. These types of exceptions are beyond your
control, and your program will not usually deal with them. Thus, these types of exceptions
are not described here.
Errors that result from program activity are represented by subclasses of Exception . For
example, divide-by-zero, array boundary, and file errors fall into this category. In general,
Search WWH ::




Custom Search