Java Reference
In-Depth Information
One important idea to grasp is that not all errors in your programs need to be signaled by exceptions.
Exceptions should be reserved for the unusual or catastrophic situations that can arise. A user entering in-
correct input to your program, for instance, is a normal event and should be handled without resorting to
exceptions. The reason for this is that dealing with exceptions involves quite a lot of processing overhead,
so if your program is handling exceptions a lot of the time it runs a lot slower than it needs to.
An exception in Java is an object that's created when an abnormal situation arises in your program. Ex-
ceptions can be created by the JVM, by standard library class methods, or by your application code. This
exception object has fields that store information about the nature of the problem. The exception is said to
be thrown — that is, the object identifying the exceptional circumstance is tossed as an argument to a spe-
cific piece of program code that has been written specifically to deal with that kind of problem. The code
receiving the exception object as a parameter is said to catch it.
The situations that cause exceptions are quite diverse, but they fall into four broad categories, as shown
in Table 7-1 .
TABLE 7-1 : Exceptions in Java
EXCEPTION
DESCRIPTION
Code or data er-
rors
For example, if you attempt an invalid cast of an object, you try to use an array index that's outside
the limits for the array, or an integer arithmetic expression has a zero divisor.
Standard method
exceptions
For example, if you use the substring() method in the String class, it can throw a StringIn-
dexOutOfBoundsException exception.
Throwing your
own exceptions
You see later in this chapter how you can throw a few of your own when you need to.
Java errors
These can be due to errors in executing the Java Virtual Machine, which runs your compiled pro-
gram, but usually arise as a consequence of an error in your program.
Before you look at how you make provision in your programs for dealing with exceptions, you should
understand what specific classes of exceptions could arise.
TYPES OF EXCEPTIONS
An exception is always an object of some subclass of the standard class Throwable . This is true for ex-
ceptions that you define and throw yourself, as well as the standard exceptions that are defined in Java's
standard packages. It's also true for exceptions that are thrown by methods in one or another of the standard
packages.
Two direct subclasses of Throwable Error and Exception — are the parent of all the standard ex-
ceptions. Both these classes have subclasses that identify specific exception conditions. Figure 7-1 shows
the Throwable class hierarchy.
FIGURE 7-1
 
 
 
 
Search WWH ::




Custom Search