Java Reference
In-Depth Information
properly checking to make sure that your code stays within the bounds of an array.
NullPointerException exceptions happen when you try to use a variable that doesn't
refer to an object yet.
CAUTION
If your program is causing runtime exceptions under any circum-
stances, you should fix those problems before you even begin
dealing with exception management.
The final group of exceptions indicates something strange and out of control is happen-
ing. An EOFException , for example, happens when you're reading from a file and the file
ends before you expected it to end. A MalformedURLException happens when a URL
isn't in the right format (perhaps a user typed it incorrectly). This group includes excep-
tions that you create to signal unusual cases that might occur in your own programs.
Exceptions are arranged in a hierarchy just as other classes are, where the Exception
superclasses are more general errors and the subclasses are more specific errors. This
organization becomes more important to you as you deal with exceptions in your own
code.
The primary exception classes are part of the java.lang package (including Throwable ,
Exception , and RuntimeException ). Many of the other packages define other excep-
tions, and those exceptions are used throughout the class library. For example, the
java.io package defines a general exception class called IOException , which is sub-
classed not only in the java.io package for input and output exceptions ( EOFException
and FileNotFoundException ) but also in the java.net classes for networking excep-
tions such as MalformedURLException .
Managing Exceptions
Now that you know what an exception is, how do you deal with one in your own code?
In many cases, the Java compiler enforces exception management when you try to use
methods that throw exceptions; you need to deal with those exceptions in your own code,
or it simply won't compile. In this section, you learn about consistency checking and
how to use three new keywords— try , catch , and finally —to deal with exceptions that
might occur.
7
 
Search WWH ::




Custom Search