当我编译以下代码时,一切正常并且输出符合预期:
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 考试。
最佳答案
如果方法抛出不是RuntimeException
子类的异常,则必须声明它抛出该Exception
>。你必须写
String reverse(String s) throws Exception {
如果你要抛出一个异常
。一旦你这样做了,你就可以正常地用 try/catch 来捕获它。
关于java - 为什么我不能用 try/catch 子句处理 Exception e?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532855/