Java Reference
In-Depth Information
If method2() declares the two exceptions, method2() will compile, but
method1() now has the same problem. If method1() decides to simply declare
the two exceptions, the problem gets pushed all the way back to main(). How-
ever, main() is at the bottom of this calling sequence, so main() does not have
anyone to declare the exceptions to. Eventually, the two exceptions need to be
handled, which means that either method2(), method1(), or main() needs to
contain a try/block for the FileNotFoundException and IOException.
The following HandleOrDeclare class shows the case in which method2()
decided to declare the exceptions and method1()decided to handle the excep-
tions. That means main() does not have to worry about anything because there
is no way for either exception to work its way down to main().
import java.io.*;
public class HandleOrDeclare
{
public static void main(String [] args)
{
System.out.println(“Inside main”);
method1(args[0]);
}
public static void method1(String fileName)
{
System.out.println(“Inside method1”);
try
{
method2(fileName);
}catch(IOException e)
{
System.out.println(“Something went wrong!”);
e.printStackTrace();
}
System.out.println(“Leaving method1”);
}
public static void method2(String fileName) throws IOException
{
System.out.println(“Inside method2”);
NotSoLazy util = new NotSoLazy(fileName);
System.out.println(util.readOneByte());
System.out.println(“Leaving method2”);
}
}
The readOneByte() method declares FileNotFoundException and
IOException. The method2() method declares only IOException,
which covers both FileNotFoundException and IOException because
FileNotFoundException is a child class of IOException. I would
recommend in this type of situation to simply declare the parent
exception, as method2() demonstrates.
Search WWH ::




Custom Search