【发布时间】:2014-08-09 15:55:55
【问题描述】:
我正在用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);
}
}
}
显示错误:
所以,我更正了以下内容:
void show() throws IOException{
它工作正常......
我又做了一个实验:
void show() throws Exception{
但它也显示错误:
据我了解,这是因为重写方法的 throws 子句应在超类方法的 throws 子句中提及确切的检查异常。
和第二种情况一样,如果我在 throws 子句中写IOException 的超类Exception,它也会显示错误。为什么?即使Exception 是所有异常的父类。
我只是做了实验...这个错误告诉我什么我不知道...
谁能解释一下它所说的内容以及在覆盖方法的throws 子句中提及检查异常的限制条件是什么?
【问题讨论】:
-
我误解了你的问题。忽略你在我的回答中读到的内容。
-
@SotiriosDelimanolis 好的...没问题..但是如果我只在派生中声明 Exception,你能说我,我可以在超类中声明 IOException 吗?请回答,不要发表评论。
标签: java exception inheritance overriding throws