为什么我不能用try/catch子句处理Exception e?

pan*_*ter 0 java exception-handling scjp throwable

当我编译以下代码时,一切正常,输出正如预期:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

计划结果:

java.lang.IllegalArgumentException
That's all folks
Run Code Online (Sandbox Code Playgroud)

但是,当我运行完全相同的代码但更改异常类型时

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
Run Code Online (Sandbox Code Playgroud)

有关使用try/catch语句无法处理的父类型Exception()有什么特别之处?为什么IllegalArgumentException()允许我用try/catch语句处理它就好了.这些是一个人在晚上保持清醒的想法与失败的恐惧,不,只是参加SCJP考试.

Lou*_*man 6

抛出不是子类的异常的方法RuntimeException必须声明它抛出它Exception.你必须写

String reverse(String s) throws Exception {
Run Code Online (Sandbox Code Playgroud)

如果你打算扔掉Exception它.一旦你这样做,你可以通过try/catch正常捕获它.