Java Reference
In-Depth Information
Figure 11.4
Output of the CatchDemo2 program when a nonexistent file is used.
Catching Exceptions and Polymorphism
Although a try block can have multiple catch blocks, the catch blocks cannot simply appear
in a random order. When an exception occurs, the catch blocks are checked in the order in
which they appear. Because of polymorphism, it is possible to write a catch block that can-
not be reached.
For example, the following try block has two catch blocks following it. The IOException is
listed first, followed by a FileNotFoundException.
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
The preceding try/catch block does not compile because the FileNotFoundException
block is an unreachable block of code. Why? Because FileNotFoundException is a child
class of IOException. Therefore, a FileNotFoundException is an IOException (don't forget
the is a relationship with polymorphism). If a FileNotFoundException occurs in the try block,
the IOException will catch it because the IOException catch block is checked first.
Another result of exceptions and polymorphism is that you can write a “catch all” block.
All exception classes are child classes of Exception, so catching an Exception catches all
exceptions, both checked and run time.
For example, the following try/catch block corrects the earlier problem with IOException
and FileNotFoundException by placing them in the correct order, and it also adds a third
catch block to catch any other type of exception that might occur.
Search WWH ::




Custom Search