Java Reference
In-Depth Information
I want to show you an example that demonstrates how declaring a method
forces it to eventually be handled. Because the readOneByte() method declares
that it throws two checked exceptions, the Handle or Declare Rule applies to
any method that wants to invoke readOneByte(). Look carefully at the follow-
ing HandleOrDeclareWrong program. The class does not compile. See if you
can determine where the problem is.
public class HandleOrDeclareWrong
{
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”);
method2(fileName);
System.out.println(“Leaving method1”);
}
public static void method2(String fileName)
{
System.out.println(“Inside method2”);
NotSoLazy util = new NotSoLazy(fileName);
System.out.println(util.readOneByte());
System.out.println(“Leaving method2”);
}
}
The compiler error occurs within method2(), as shown in Figure 11.6. Within
method2(), a call to readOneByte() is made, so method2() must handle or
declare the exceptions declared by readOneByte().
We have two ways to fix the compiler error in Figure 11.6:
method2() can try and catch the FileNotFoundException and
IOException, thereby handling the exceptions.
■■
method2() can declare the two exceptions.
■■
Figure 11.6
The compiler is enforcing the Handle or Declare Rule.
Search WWH ::




Custom Search