Java Reference
In-Depth Information
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;
}catch(Exception e)
{
e.printStackTrace();
}
Notice that the Exception catch block does not contain a return statement, so the cur-
rent method keeps executing. The other two catch blocks cause the method to pop off
the call stack because they return a value to the calling method. These are merely design
decisions.
I want you to look at the next try/catch block and try to determine how it filters excep-
tions that may occur.
try
{
//Protected code
}catch(RuntimeException r)
{
System.out.println(“Just caught a runtime exception”);
r.printStackTrace();
}catch(Exception e)
{
System.out.println(“Just caught a checked exception”);
e.printStackTrace();
}
You can tell by the println() statements that the first catch block catches all runtime excep-
tions, whereas the second catch block catches all checked exceptions. The RuntimeException
catch block has to appear before the Exception catch block because RuntimeException is a
child class of Exception.
Handle or Declare Rule
Java has a rule that is strictly enforced regarding checked exceptions; it is
referred to as the Handle or Declare Rule. The rule states simply that a checked
exception must be either handled or declared. Handling an exception involves
catching the exception. Declaring an exception involves a method using the
Search WWH ::




Custom Search