Javadoc,Eclipse 中的“未抛出异常”

Javadoc, " exception not thrown" in Eclipse

创建 javaodc 时,您描述了您的方法可以抛出的异常,对吗?

看例子:

public  void createLogFile() {
    try {
        file.createNewFile();
        fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);

    } catch (IOException e) {
        MainScene.ausgabeText.setText("Fehler bei dem Erstellen des Log Files.");

    }
}

这是我关于此方法的 javadoc。

/**
 * A logfile will be created
 * @exception IOException
 *                When the log file coulndt be created ( just a test :-))
 */

导出到 javadoc 时,Eclipse 告诉我:

error: exception not thrown: java.io.IOException
 * @exception IOException

但是 Eclipse 要我捕获那个异常。

为什么我的 Eclipse 给我上面的错误消息?

该函数应该抛出您在 javadoc 注释中定义的异常。实际上你并没有抛出 IOException。你抓住了。

public  void createLogFile() throws IOException {
    try {
        file.createNewFile();
        fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);

    } catch (IOException e) {
        MainScene.ausgabeText.setText("Fehler bei dem Erstellen des Log Files.");

    }
}

您不应将 IOException 包含到 Javadocs @throws 子句中,因为您永远不会抛出一个子句。

显然,Eclipse 试图确保方法 throws 子句的列表与 Javadocs 中的列表匹配。

 // valid
 /**
  * ...
  * @throws IOException description
  */
 void createLogFile() throws IOException { ... }

 // invalid
 /**
  * ...
  * @throws IOException description
  */
 void createLogFile() { ... }

 // bad documentation
 /**
  * ...
  */
 void createLogFile() throws IOException { ... }

考虑文档的叙述风格。您可以说 "Creates a logfile".

而不是 "A logfile will be created"

有两种处理方式 Exception:

  1. 在方法内部捕获它,在方法外部没有人会知道异常发生,所以你can't write in the Javadoc这个方法会抛出异常(隐式扔到外面)

    /**
    */
    public void createLogFile() {
        try {
            //...
        } catch (IOException e) {
            //...   
        }
    }
    
  2. 你让异常传播到你的方法之外,在这种情况下你 can writ in the Javadoc 这个方法可以抛出异常(隐含地 抛出到外面 )

    /**
    * @throws IOException When the log file coulndt be created
    */
    public void createLogFile() throws IOException  {
       //...
    }
    

注意:标签 @throws@exception 是同义词。 Ref

当你写一个方法时,实现对调用者是隐藏的(忽略你可以看到方法实现的事实,如果你自己写的话)。有时在您实现一个方法时,您会遇到异常(或者您甚至可能会抛出自定义异常)。您可以做两件事:

赶上

当您想要处理异常时,您可以捕获它。这意味着您知道某些事情 可能 出错并且您知道该怎么做,以便在发生这种情况时程序可以以可预测的方式继续。

由于调用者看不到您的实现,因此对他们来说是完全隐藏的。

投掷

当你不想处理异常时,因为更适合让调用者知道这个问题并处理它。在这种情况下,您不 catch 它并通过 throws 关键字将 Exception 添加到方法中。执行此操作时,您 可以 在方法 Javadoc 中添加 @throws@exception 注释,以准确地告诉调用者他们预计何时会收到特定异常。

由于该注释仅用于告诉调用者何时期望以及如何正确处理该方法抛出的异常,因此添加该方法未抛出的任何异常是没有意义的。

请注意,您只需要 throws 检查异常。方法不需要通过 throws 列出未经检查的异常,因为它们通常是由编写不当的代码引起的。