私の推測では、スローできる例外タイプとしてメソッドによって宣言されていない例外サブクラスをスローしようとしていると思います。
次の例は動作します
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws Exception{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
ただし、この例ではエラーが発生します。
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
2 番目の例では、RuntimeException ではなく単に Exception をキャッチしていることに注意してください。RuntimeException を宣言していても、宣言されていないスローである Exception をスローすると、コンパイルされません。
はい、例外は RuntimeException ですが、コンパイラはそれを知りません。
3 番目の実例を考えてみました。宣言したのと同じ型をスローするため、これも機能します。(唯一の変更点は catch ブロックであることに注意してください)
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (RuntimeException e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
これら3つの答えすべての違いを理解する必要があります