Java 重写 throws 子句

Mik*_*ike 5 java methods overriding signature throws

我正在通过阅读 SG Ganesh 和 Tushar Sharma 撰写的书来学习 OCJP 考试。第346页有一段文字说:

\n\n
\n

如果您尝试更改 throws 子句会怎样?有多种方法可以更改重写方法中的 throws 子句,包括以下几种
:不提供任何 throws 子句。
\n b.列出要抛出的更一般的检查异常。
\n c. 除了基本方法中给定的已检查异常之外,还列出更多已检查异常。
\n 如果尝试这三种情况中的任何一种,\xe2\x80\x99 将收到编译器错误。例如,尝试不在实现 IntReader 接口的类的 readIntFromFile() 方法中提供 throws 子句。

\n\n
public int readIntFromFile() {\n    Scanner consoleScanner = new Scanner(new File("integer.txt"));\n    return consoleScanner.nextInt();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

你\xe2\x80\x99会得到这个编译器错误:\xe2\x80\x9cun报告异常FileNotFoundException; 必须被捕获或声明为抛出。\xe2\x80\x9d
\n 总而言之,基类方法\xe2\x80\x99s throws 子句是它提供给该方法的调用者的契约:
\n 它表示调用者应该处理列出的异常或在其 throws 子句中声明这些异常。当重写基本方法时,派生方法也应遵守该约定。基本方法的调用者准备只处理基本方法中列出的异常,因此重写方法不能抛出更一般的异常或除列出的已检查异常之外的异常。
\n 但是,请注意,派生类方法\xe2\x80\x99s throws 子句应遵循基方法\xe2\x80\x99s throws 子句的约定的讨论仅限于受检查的异常。与基类 method\xe2\x80\x99s throws 子句相比,仍可以在合约中添加或删除未经检查的异常。例如,请考虑以下情况:

\n\n
public int readIntFromFile() throws IOException, NoSuchElementException {\n    Scanner consoleScanner = new Scanner(new File("integer.txt"));\n    return consoleScanner.nextInt();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是一个可接受的 throws 子句,因为可以从 readIntFromFile() 方法抛出 NoSuchElementException。此异常是未经检查的异常,当 nextInt() 方法无法从文件中读取整数时会抛出该异常。这是一种常见情况,例如,如果您有一个名为integer.txt 的空文件;尝试从此文件读取整数将导致此异常。

\n
\n\n

我有点担心“a”这一点。它表示如果您不提供任何 throws 子句,则代码将无法编译。但是当我学习 OCA 时,我记得我读到您可以提供相同的 throws 子句、更具体的 Exception 或根本不提供 throws 子句,并且代码仍将编译,并且这些仅适用于受检查的异常。\nI\'我尝试做一些测试,但我无法得到 \xe2\x80\x9cunreported 异常 FileNotFoundException; 必须被抓住或\n声明被抛出。\xe2\x80\x9d。我记得我见过它,但不知道是在什么条件下看到的。

\n

Dic*_*ici 2

正如马努蒂所说,这本书是错误的。你绝对可以有更精确的或无例外的,但你不能有更一般的:

interface A {
    void meth() throws IOException;
}

class B implements A {
    @Override
    void meth() throws FileNotFoundException { } // compiles fine
}

class C implements A  {
    @Override
    void meth() { } // compiles fine
}

class D implements A  {
    @Override
    void meth() throws Exception { } // compile error
}
Run Code Online (Sandbox Code Playgroud)