次のコードがあり、コンパイル エラーが発生しています。
// Program1 -- コンパイル エラー
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");
}
}
しかし、いくつかの catch ブロックを追加した後、次のコードは機能します。
// プログラム 2 - コンパイル エラーなし
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");
}
}
/////////////////////////////////////////////// ////////// "System.out.println("Hi");" で到達できないコード 不必要な catch ブロックを追加して問題を解決するにはどうすればよいでしょうか?