class Y {
public static void main(String[] args) throws RuntimeException{//Line 1
try {
doSomething();
}
catch (RuntimeException e) {
System.out.println(e);
}
}
static void doSomething() throws RuntimeException{ //Line 2
if (Math.random() > 0.5) throw new RuntimeException(); //Line 3
throw new IOException();//Line 4
}
}
2 種類の例外 (Line4 の IOException と Line3 の RunTimeException) をスローすると、1 行目と 2 行目の throws 句で「IOException」を指定するまでプログラムがコンパイルされないことがわかりました。
一方、「スロー」を逆にして IOException がスローされたことを示すと、以下に示すように、プログラムは正常にコンパイルされます。
class Y {
public static void main(String[] args) throws IOException {//Line1
try {
doSomething();
}
catch (RuntimeException e) {
System.out.println(e);
}
}
static void doSomething() throws IOException {//Line 2
if (Math.random() > 0.5) throw new RuntimeException();//Line 3
throw new IOException();//Line 4
}
}
RuntimeException もスローされる (3 行目) にもかかわらず、常に IOException に「スロー」を使用する必要があるのはなぜですか?