Java Reference
In-Depth Information
To demonstrate the Handle or Declare Rule, let's look at an example similar to
the ExceptionDemo earlier in this section. (By the way, ExceptionDemo threw an
ArithmeticException , which is a runtime exception, so the Handle or Declare Rule did
not apply to its method3 .) In the following CheckedDemo class, line 14 calls the static method
Class.forName , which declares the checked exception ClassNotFoundException . Study the
following code and see if it compiles:
1. public class CheckedDemo {
2. public void method1() {
3. System.out.println(“Inside method1”);
4. method2();
5. }
6.
7. public void method2() {
8. System.out.println(“Inside method2”);
9. method3();
10. }
11.
12. public void method3() {
13. System.out.println(“Inside method3”);
14. Class c = Class.forName(“java.lang.String”);
15. System.out.println(“class name: “ + c.getName());
16. }
17.}
Because line 14 invokes a method that declares a checked exception, the Handle
or Declare Rule applies. Because the ClassNotFoundException is neither handled nor
declared, this code does not compile and the following compiler error is generated:
CheckedDemo.java:14: unreported exception java.lang.ClassNotFoundException; must
be caught or declared to
be thrown
Class c = Class.forName(“java.lang.String”);
^
There are two options for method3 : either include a try-catch statement around line
14 that catches a ClassNotFoundException , or declare the exception using the throws
keyword. Let's have method3 declare the exception instead of handling it:
12. public void method3() throws ClassNotFoundException {
13. System.out.println(“Inside method3”);
14. Class c = Class.forName(“java.lang.String”);
15. System.out.println(“class name: “ + c.getName());
16. }
Search WWH ::




Custom Search