Java Reference
In-Depth Information
With these features, you can add a whole new dimension to the behavior and design of
your classes, your class hierarchy, and your overall system. Your class and interface defi-
nitions describe how your program is supposed to behave given the best circumstances.
By integrating exception handling into your program design, you can consistently
describe how the program will behave when circumstances are not ideal and allow peo-
ple who use your classes to know what to expect in those cases.
Exception Classes
At this point, it's likely that you've run into at least one Java exception—perhaps you
mistyped a method name or made a mistake in your code that caused a problem. Maybe
you tried to run a Java application without providing the command-line arguments that
were needed and saw an
ArrayIndexOutOfBoundsException
message.
Chances are, when an exception occurred, the application quit and spewed a bunch of
mysterious errors to the screen. Those errors are exceptions. When your program stops
without successfully finishing its work, an exception is thrown. Exceptions can be
thrown by the virtual machine, thrown by classes you use, or intentionally thrown in your
own programs.
The term “thrown” is fitting because exceptions also can be “caught.” Catching an excep-
tion involves dealing with the exceptional circumstance so that your program doesn't
crash—you learn more about this later today.
The heart of the Java exception system is the exception itself. Exceptions in Java are
instances of classes that inherit from the
Throwable
class. An instance of a
Throwable
class is created when an exception is thrown.
Throwable
has two subclasses:
Error
and
Exception
. Instances of
Error
are internal
errors involving the Java virtual machine (the runtime environment). These errors are
rare and usually fatal to the program; there's not much that you can do about them (either
to catch them or to throw them yourself).
The class
Exception
is more relevant to your own programming. Subclasses of
Exception
fall into two general groups:
Runtime exceptions (subclasses of the class
RuntimeException
) such as
ArrayIndexOutofBoundsException
,
SecurityException
, and
NullPointerException
n
Other exceptions such as
EOFException
and
MalformedURLException
n
Runtime exceptions usually occur because of code that isn't very robust. An
ArrayIndexOutofBounds
exception, for example, should never be thrown if you're