有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java LocalDate。format(DateTimeFormatter formatter)不在方法签名中声明“throws”

我查看了LocalDate API的java源代码,发现这些方法缺少throws声明。然而,javadoc明确提到,该方法可能引发DateTimeException。下面是来自Java8的LocalDateAPI的源代码

/**
 * Formats this date using the specified formatter.
 * <p>
 * This date will be passed to the formatter to produce a string.
 *
 * @param formatter  the formatter to use, not null
 * @return the formatted date string, not null
 * @throws DateTimeException if an error occurs during printing
 */
@Override  // override for Javadoc and performance
public String format(DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.format(this);
}
  1. 这是否应该是声明抛出异常的方法的正确方法(我希望在方法签名中抛出,使客户机能够正确处理异常,但除非读取javadoc,否则这不会给客户机提供异常的线索)

请告诉我,我是否错过了一些正确理解这一点的东西


共 (1) 个答案

  1. # 1 楼答案

    DateTimeException是一个未经检查的异常,因此不必声明为方法

    为什么LocalDate#format要声明它?因为它可以由它自己将执行委托给的方法抛出。在调用链之后,我们看到DateTimeFormatter.formatTo(TemporalAccessor, Appendable)是执行实际工作的方法,它正在抛出异常;没有一种中间方法能够捕捉/处理它

    public void formatTo(TemporalAccessor temporal, Appendable appendable) {
        ...
        try {
            ...
        } catch (IOException ex) {
            throw new DateTimeException(ex.getMessage(), ex);
        }
    }
    

    我相信这确实是一个很好的异常文档的例子(记录应该预料到的异常,不管它们是否经过检查,即使您没有明确地将它们放入所讨论的方法中)