Java Reference
In-Depth Information
13. method3();
14. }
15.
16. public void method3() throws ClassNotFoundException {
17. System.out.println(“Inside method3”);
18. Class c = Class.forName(“java.lang.String”);
19. System.out.println(“class name: “ + c.getName());
20. }
21.
22. public static void main(String [] args) {
23. System.out.println(“Inside main”);
24. new CheckedDemo().method1();
25. System.out.println(“End of main”);
26. }
27.}
I should point out that although the
Class.forName
method might throw a
ClassNotFoundException
, it is not thrown in this example on line 18 because the
String
class is found by the JVM's class loader. The output of running this program is
Inside main
Inside method1
Inside method2
Inside method3
class name: java.lang.String
End of main
Suppose we modify line 18 so that it attempts to load a class that is not found. A simple
typo can cause the exception to be thrown. Try and determine the output of
CheckedDemo
if
line 18 is the following:
18. Class c = Class.forName(“java.lang.string”);
Here is the sequence of events that occurs in this case:
1.
main
is called, which invokes
method1
.
2.
method1
invokes
method2
.
3.
method2
invokes
method3
.
4.
Line 18 throws a
ClassNotFoundException
, which is not caught in
method3
.
method3
is
immediately popped off the call stack and the exception is thrown to
method2
.
5.
method2
does not catch the exception, so it is immediately popped off the call stack
and the exception is thrown to
method1
.
Search WWH ::
Custom Search