Java Reference
In-Depth Information
Declaring the exception fi xes the compiler error on line 14, but the CheckedDemo class
still does not compile. We have simply moved the compiler error up to line 9:
CheckedDemo.java:9: unreported exception java.lang.ClassNotFoundException; must
be caught or declared to be thrown
method3();
^
Because method3 now declares a checked exception, method2 needs to handle or declare
the ClassNotFoundException . Notice how declaring a checked exception does not mean
we can ignore that exception; it simply pushes the responsibility to the calling method.
method2 now has two options: catch the ClassNotFoundException or declare it. Let's
declare it again:
7. public void method2() throws ClassNotFoundException {
8. System.out.println(“Inside method2”);
9. method3();
10. }
Again, this fi xes the compiler error on line 9, but the CheckedDemo class still does not
compile. Now the error message is on line 4:
CheckedDemo.java:4: unreported exception java.lang.ClassNotFoundException; must
be caught or declared to be thrown
method2();
^
method1 must either handle or declare the ClassNotFoundException . Let's handle it this
time, which should take care of the compiler error. See if you can determine the output of
the following version of CheckedDemo :
1. public class CheckedDemo {
2. public void method1() {
3. System.out.println(“Inside method1”);
4. try {
5. method2();
6. }catch(ClassNotFoundException e) {
7. e.printStackTrace();
8. }
9. }
10.
11. public void method2() throws ClassNotFoundException {
12. System.out.println(“Inside method2”);
Search WWH ::




Custom Search