Java 异常和抛出子句

Java exceptions and throw clauses

JLS 在其 8.4.8.3 子句中提到了覆盖包含 throws 子句的方法,但他们试图通过这个表达的意思并不完全清楚:

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

  • If m2 has a throws clause that mentions any checked exception types, then m1 must have a throws clause, or a compile-time error occurs.

什么类型的检查异常 m2 应该在它的 throws 子句中抛出?

它说,如果您的 child class 抛出 parent 没有的检查异常,那么它将导致编译时错误。

考虑一下:

class A {
    public void testMethod() {}
}

class B extends A {
    public void testMethod() throws FilNotFoundException {}
}

这将引发编译时错误。此外它说,要解决这个问题,您可能需要 parent 的方法来抛出 FileNotFoundException。

代码中的示例:

class B implements A {

  @Override
  void m() throws SomeException {
    /* ... */
  }
}

不允许的内容:

interface A {

  void m(); // This is not allowed
}

允许的内容:

interface A {

  void m() throws SomeException;
}

甚至:

interface A {

  void m() throws Exception;
}

编辑:

你引用的第二个要点:

  • For every checked exception type listed in the throws clause of m2, that same exception class or one of its supertypes must occur in the erasure (§4.6) of the throws clause of m1; otherwise, a compile-time error occurs.

What type of checked exception m2 should throw in its throws clause?

m2只能throws超类中重写方法的throws子句中异常类的全部或部分

例如:

class Base                     
{
    void amethod() { }
}

class Derv extends Base
{
    void amethod() throws Exception { } //compile-time error
}