I have the following codes, and it is giving me a compilation error.
// Program1 -- Compilation error
public class ExceptionExample {
public static void main(String[] a) {
try {
method();
} catch (ClassCastException p) {} catch (Exception e) {
System.out.println(" Exception");
}
}
public static void method() {
try {
throw new NullPointerException();
} finally {
System.out.println("Hello");
}
System.out.println("Hi");
}
}
But the following code works after I added some catch blocks.
// Program 2 - No Compilation error
public class ExceptionExample {
public static void main(String[] a) {
try {
method();
} catch (ClassCastException p) {
} catch (Exception e) {
System.out.println(" Exception");
}
}
public static void method() {
try {
throw new NullPointerException();
}
// Below catch block has been added
catch (ClassCastException p) {
}
finally {
System.out.println("Hello");
}
System.out.println("Hi");
}
}
//////////////////////////////////////////////////////////// Unreachable code at "System.out.println("Hi");" I am wondering, how can adding unnecessary catch blocks solve my problem?