在子类中抛出异常的标准是什么

6 java polymorphism overriding exception

到目前为止我所知道的是,如果重写超类方法,子类应抛出相同的异常或异常的子类.

例如:

这是对的

class SuperClass {
    public int doIt(String str, Integer... data)throws ArrayIndexOutOfBoundsException{
 String signature = "(String, Integer[])";
 System.out.println(str + " " + signature);
 return 1;
 }
}

public final class SubClass extends SuperClass {
    public int doIt(String str, Integer... data) throws ArrayIndexOutOfBoundsException {
        String signature = "(String, Integer[])";
        System.out.println("Overridden: " + str + " " + signature);
        return 0;
    }

    public static void main(String... args) {
        SuperClass sb = new SubClass();
        try {
            sb.doIt("hello", 3);
        } catch (Exception e) {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是不正确的

class SuperClass {
    public int doIt(String str, Integer... data)throws ArrayIndexOutOfBoundsException{
 String signature = "(String, Integer[])";
 System.out.println(str + " " + signature);
 return 1;
 }
}

public final class SubClass extends SuperClass {
    public int doIt(String str, Integer... data) throws Exception {
        String signature = "(String, Integer[])";
        System.out.println("Overridden: " + str + " " + signature);
        return 0;
    }

    public static void main(String... args) {
        SuperClass sb = new SubClass();
        try {
            sb.doIt("hello", 3);
        } catch (Exception e) {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我的问题是,为什么这个代码块被编译器认为是正确的?

class SuperClass {
    public int doIt(String str, Integer... data)throws ArrayIndexOutOfBoundsException{
 String signature = "(String, Integer[])";
 System.out.println(str + " " + signature);
 return 1;
 }
}

public final class SubClass extends SuperClass {
    public int doIt(String str, Integer... data) throws RuntimeException {
        String signature = "(String, Integer[])";
        System.out.println("Overridden: " + str + " " + signature);
        return 0;
    }

    public static void main(String... args) {
        SuperClass sb = new SubClass();
        try {
            sb.doIt("hello", 3);
        } catch (Exception e) {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

sie*_*egi 6

这是因为在Java中,每个方法都可以随时抛出一个RuntimeException(或一个Error).它甚至不需要在throws方法签名的部分声明.因此,有可能还抛出一个异常,它是在重写方法中声明的异常类型,只要它仍然是子类型RuntimeException.

有关此行为的规范,请参阅Java语言规范的第11章(例外),尤其是11.1.1.定义checked(需要在throws子句中指定)和unchecked(不需要在throws子句中指定)异常的异常种类.