java - 在覆盖方法中检查 'throws' 的异常

标签 java exception inheritance overriding throws

我在java中用方法覆盖练习异常处理机制......我的代码如下:

class base {
    void show() {    
        System.out.println("in base class method");    
    }
}

class derived extends base {
    void show() throws IOException {    
        System.out.println("in derived class method");
        throw new IOException();
    }
}

class my {
    public static void main(String[] args) {  
        try {
            base b = new derived();
            b.show();
        }    
        catch (IOException e) {
            System.out.println("exception occurred at :" + e);
        }   
    }
}

显示错误:

cmd window

因此,我更正了以下内容:

void show() throws IOException{

它工作正常......

我又做了一个实验:

void show() throws Exception{

但它也显示错误:

cmd window

据我了解,这是因为重写方法的 throws 子句应该在父类(super class)方法的 throws 子句中提及确切的检查异常。

与第二种情况一样,如果我在 throws 子句中写入 IOException 的父类(super class) Exception,它也会显示错误。为什么?即使 Exception 是所有异常的父类。

我刚刚试验过...这个错误说明了什么我不知道...

任何人都可以解释它说的是什么以及在覆盖方法的 throws 子句中提及检查异常的约束是什么?

最佳答案

样本中有两个相关的错误:

1) 您的基类方法为派生类方法提供了"template"基本标准

因此,基类应该声明一个超集,即派生类的相同异常类或基异常类。您不能声明它什么都不抛出,因为那样的话标准将不匹配。

所以如果你的派生类方法是这样的:

class Derived extends Base {
    void show() throws IOException {
        //...
    }
}

那么基类方法“必须”是:

class Base {
    void show() throws /*Same or base classes of IOException*/ {
        //...
    }
}

所以这两个都有效:

class Base {
    void show() throws Exception {
        //...
    }
}

class Base {
    void show() throws Throwable {
        //...
    }
}

2) 当您尝试上述操作时,show 方法的整体声明现在变成了throws Exception。因此,任何使用此 show 的人都必须捕获该异常。

在您的 main 方法中,您正在捕获 IOException。这将不再有效,编译器会提示“好吧,你正在捕获 IOException,那么来自 Exception 的所有其他可能性呢?”这是您显示的第二个错误。

要解决此问题,请更改 main 方法 catch 以包含在基类中声明的 Exception:

class My {
    public static void main(String[] args) {
        try {
            base b = new derived();
            b.show();
        }
        /* NOTE: CHANGED FROM IOException TO Exception */
        catch (Exception e) {
            System.out.println("exception occurred at :" + e);
        }   
    }
}

关于java - 在覆盖方法中检查 'throws' 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25220364/

相关文章:

perl - Mojo $c->回复->异常 vs 死亡?

java - JPanel 已添加到切换按钮单击上的其他 Jpanel 上

java - 使用 CouchBase-Lite 移动设备进行单元测试,无需 Android 应用程序上下文

scala - 捕获 Scala 2.8 RC1 中的所有异常

python - 哪个异常通知子类应该实现一个方法?

c++ - 使用具有同名方法的派生类的对象访问基类的方法

java - 如何用gson解析这个

java - 如何反转或求补 Java 中返回 boolean 值的函数的输出

c++ - 继承:构造函数,像c++11中基类的数组成员一样初始化C

java:关于重写方法的继承问题