Java Reference
In-Depth Information
exceptions (the IO stands for input/output ). These exceptions include two of its sub-
classes, EOFException and FileNotFoundException . By catching IOException , you also
catch instances of any IOException subclass.
To catch several different exceptions that aren't related by inheritance, you can use multi-
ple catch blocks for a single try , like this:
try {
// code that might generate exceptions
} catch (IOException ioe) {
System.out.println(“Input/output error”);
System.out.println(ioe.getMessage());
} catch (ClassNotFoundException cnfe) {
System.out.println(“Class not found”);
System.out.println(cnfe.getMessage());
} catch (InterruptedException ie) {
System.out.println(“Program interrupted”);
System.out.println(ie.getMessage());
}
In a multiple catch block, the first catch block that matches is executed and the rest is
ignored.
You can run into unexpected problems by using an Exception
superclass in a catch block followed by one or more of its sub-
classes in their own catch blocks. For example, the input/output
exception IOException is the superclass of the end-of-file excep-
tion EOFException . If you put an IOException block above an
EOFException block, the subclass never catches any exceptions.
CAUTION
The finally Clause
Suppose that there is some action in your code that you absolutely must do, no matter
what happens, regardless of whether an exception is thrown. This is usually to free some
external resource after acquiring it, to close a file after opening it, or something similar.
Although you could put that action both inside a catch block and outside it, that would
be duplicating the same code in two different places, which is a situation you should
avoid as much as possible in your programming.
Instead, put one copy of that code inside a special optional block of the try - catch state-
ment that uses the keyword finally :
Search WWH ::




Custom Search