java - 在子类中抛出错误、异常和运行时异常

标签 java

我试图理解为什么子类不能覆盖父类中的方法实现来捕获异常但在捕获错误时没有问题的区别,

例如在下面的场景中,当我从 throws 子句中删除“Exception”时,它编译正常。

class Supertest {

    public void amethod(int i, String s) {

    }

}

public class test extends Supertest {

    public void amethod(int i, String s) throws Error, Exception {

    }

}

最佳答案

Error 是未经检查的异常。 Exceptionchecked exception .就这么简单。所以有这样的代码应该是合理的:

Supertest x = new test();
x.amethod(10, "foo");

... 但是 test.amethod() 试图对调用者强加一个已检查的异常,以便调用者必须捕获它或传播它。由于它覆盖的方法未声明该异常,因此覆盖方法也不能。

如评论中所述,从根本上说,您不能用“限制性更强”的方法覆盖一种方法 - 对原始方法的任何调用都必须对覆盖有效。

来自 section 8.4.8.3 JLS 的:

More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. Then:

  • If n has a throws clause that mentions any checked exception types, then m must have a throws clause, or a compile-time error occurs.
  • For every checked exception type listed in the throws clause of n, that same exception class or one of its supertypes must occur in the erasure (§4.6) of the throws clause of m; otherwise, a compile-time error occurs.

关于java - 在子类中抛出错误、异常和运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18878588/

相关文章:

java - 安卓号码扫描仪

java - Webdriver:查找并单击隐藏元素,其中 id 不断变化

java - java 上的数组参数行为

java - spring-rabbit 中每个主题的并发消费者

java - OpenGL VBO - 数组步幅错误?

java - 正则表达式获取直到一个字符的值

java - 使用 GWT 在 Donut Highchart 上单击事件

java - 自定义 JSP 页面

java - 为什么我的 hibernate join 只返回一张表的查询?

java - x.person 上的@OneToOne 或@ManyToOne 引用未知实体 : y. Person - 继承问题