Java Reference
In-Depth Information
All the other classes derived from the class Exception are checked exceptions so the compiler verifies that
you either have provided code to handle the exception in a method where the exception may be thrown or
that you've indicated that the method can throw such an exception. If you do neither, your code doesn't
compile. You look more at how you ensure that the code does compile in the next two sections.
Apart from those that are subclasses of RuntimeException , all exceptions thrown by methods in the Java
class library are checked. In Chapter 8 you look at input and output where the code is liberally sprinkled
with provisions for exceptions being thrown.
NOTE You see later in this chapter that when you want to define your own exceptions, you do
this by subclassing the Exception class. Wherever your exception can be thrown by a method,
the compiler verifies either that it is caught in the method or that the method definition indic-
ates that it can be thrown by the method, just as it does for the built-in exceptions.
DEALING WITH EXCEPTIONS
As I discussed in the previous sections, if your code can throw exceptions other than those of type Error
or type RuntimeException (you can assume that I generally include the subclasses when I talk about Er-
ror and RuntimeException exceptions), you must do something about it. Whenever you write code that
can throw a checked exception, you have a choice. You can supply code within the method to deal with any
exception that is thrown, or you can essentially ignore it by enabling the method containing the exception-
throwing code to pass it on to the code that invoked the method.
Let's first see how you can pass an exception on.
Specifying the Exceptions a Method Can Throw
Suppose you have a method that can throw an exception that is neither a subclass of RuntimeException
nor of Error . This could be an exception of type IOException , for example, which can be thrown if your
method involves some file input or output operations. If the exception isn't caught and disposed of in the
method, you must at least declare that the exception can be thrown. But how do you do that?
You do it simply by adding a throws clause in the method signature. Suppose you write a method that
uses the methods from classes that support input/output that are defined in the package java.io . You see
in the chapters devoted to I/O operations that some of these can throw exceptions represented by objects of
classes IOException and FileNotFoundException . Neither of these is a subclass of RuntimeException
or Error , so the possibility of an exception being thrown needs to be declared. Because the method can't
handle any exceptions it might throw, if only for the simple reason that you don't know how to do it yet, it
must be defined as:
double myMethod() throws IOException, FileNotFoundException {
// Detail of the method code...
}
Search WWH ::




Custom Search