You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否需在generateMessage方法文档中声明嵌套方法抛出的异常?

问题:是否需要在generateMessage方法的Javadoc中包含嵌套方法抛出的异常?

我编写了如下Java代码:

/**
 * Generates a message and saves it to a file where placeholders '%s' are replaced with values
 * provided during runtime from properties file.
 *
 * @param formattedMessage the formatted message where placeholders are replaced to '%s'
 * @param placeholderKeys  list with placeholder keys
 * @return string
 */
public String generateMessage(String formattedMessage, List<String> placeholderKeys,
                              String inputFilePath, String outputFilePath) {
    pathValidator.throwExceptionIfInputPathInvalid(inputFilePath);
    pathValidator.throwExceptionIfOutputPathInvalid(outputFilePath);
    List<String> placeholderValues = fileUtil.getPlaceholderValues(inputFilePath, placeholderKeys);
    String generatedMessage = String.format(formattedMessage, placeholderValues.toArray());
    fileUtil.writeToFile(outputFilePath, generatedMessage);
    return generatedMessage;
}

如你所见,该方法调用了两个仅用于抛出异常的方法,其中一个方法的代码如下:

/**
 * Throws exceptions if input file path is invalid
 *
 * @throws InvalidInputException         if input is blank
 * @throws InvalidFileExtensionException if provided file is not of a properties type
 * @throws PathNotValidException         if provided output file path is not valid
 * @throws FileNotFoundException         if provided input file is not found
 */
public void throwExceptionIfInputPathInvalid(String path) {
    throwExceptionIfOutputPathInvalid(path);
    if (!InputValidator.isExtensionValid(new File(path), ".properties"))
        throw new InvalidFileExtensionException("File should be of properties type");
    if (!Files.exists(Paths.get(path))) throw new FileNotFoundException();
}

请问是否需要在generateMessage方法的文档中包含这些嵌套方法抛出的异常?


回答

肯定要把这些嵌套方法抛出的异常加到generateMessage的Javadoc里,理由很实在:

  • 对调用这个方法的开发者来说,没人愿意为了搞清楚可能出啥异常,还要扒开内部调用的throwExceptionIfInputPathInvalid这类方法看细节。直接把所有可能抛出的异常列在generateMessage的文档里,能让使用者一眼就知道要处理哪些异常场景,用起来更省心。

  • 这也是Javadoc的规范要求:只要方法会抛出异常(不管是自己抛的还是内部方法抛的),只要这些异常是该方法对外表现出来的行为,就得用@throws标签说明。对调用者而言,这些异常就是generateMessage抛出来的,和内部谁触发的无关。

  • 方便后续维护:要是以后内部校验方法改了异常类型,同步更新generateMessage的文档,就能保证文档和实际代码行为一致,不会坑到其他开发者。

当然,如果是系统里人人都知道的通用基础异常,可以适当简化,但像InvalidFileExtensionException这种业务相关的特定异常,必须明确标注清楚。

内容的提问来源于stack exchange,提问作者Klaus Köhler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:24:51