exception-handling - 异常处理中的方法覆盖
问题描述
在异常处理中,众所周知,如果超类方法不声明异常,子类重写方法不能声明已检查异常,但可以声明未检查异常。为什么这样?考虑以下示例:
import java.io.*;
class Parent {
void msg() {
System.out.println("parent");
}
}
class TestExceptionChild extends Parent {
void msg() throws IOException {
System.out.println("TestExceptionChild");
}
public static void main(String args[]) {
Parent p = new TestExceptionChild();
p.msg();
}
}
我试过的:
我们在这里得到编译错误。如果我需要在重写方法“msg”中读取文件,那么我必须在此处提及“throws IOException”。但是java不允许它们。谁能解释一下?
解决方案
您需要记住一件事,如果您使用 throws 关键字,那么出现的任何异常都将被转发到调用链中,并且如果在编译时重写,编译器会检查天气,重写的方法是否存在于父类中,并且 JVM 执行子类方法. 因此,基本上从父方法调用子方法,因此如果子方法抛出任何异常,否则它应该能够处理检查的异常,否则 CE .. 我希望它有帮助:)
推荐阅读
- eclipse - 没有创建 jUnit 测试类的选项
- jquery - svg路径上的jQuery wrap隐藏路径
- linux-kernel - 使用 Linux 内核 API 进行数据字节序的可移植转换
- qt - 调整布局大小等于 MainWindow
- ibm-midrange - 枚举 QSYS.LIB 内所有库中的对象
- php - 线程 PHP 中的 Sleep()
- javascript - 删除 https://{endpoint}/{bucketName} 避免评论 Javascript
- android - OpenWeatherMap 的自定义 TileProvider 不显示降水图块
- android - 我可以使用 lambda 表达式来替换仅用一个抽象方法实例化抽象类吗?
- elasticsearch - Kibana 中不显示字段