次のコードをコンパイルすると、すべてがうまくいき、出力は期待どおりになります。
class Propogate {
public static void main(String[] args) {
Propogate obj = new Propogate();
try {
obj.reverse("");
} catch (IllegalArgumentException e) {
System.out.println(e);
} finally {
System.out.println("That's all folks");
}
}
String reverse(String s) {
if(s.length() == 00) {
throw new IllegalArgumentException();
}
String reversed = "";
for(int i=s.length() - 1; i >= 0; --i) {
reversed += s.charAt(i);
}
return reversed;
}
}
プログラムの結果:
java.lang.IllegalArgumentException
That's all folks
ただし、まったく同じコードを実行しても例外タイプを変更すると
IllegalArgumentException to plain old exception all I get is:Propogate.java:14: error:
unreported exception Exception; must be caught or declared to be thrown
throw new Exception();
^
1 error
親型の Exception() は、try / catch ステートメントで処理できないという特別な点は何ですか? IllegalArgumentException() を使用すると、try / catch ステートメントで問題なく処理できるのはなぜですか。これらは、不合格、いや、SCJP 試験を受けることへの恐怖で夜も眠れずに起きていることの考えです。