當我編譯下面的代碼一切順利,並預期輸出:爲什麼我不能用try/catch子句處理Exception e?
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考試纔會失敗。
你更改爲'Exception'的哪個? 「扔」或「抓」? – rgettman
我改變了投擲和捕捉的類型。 – paniclater
阿加!這個詞是「傳播」......不是「傳播」。 –