【发布时间】:2018-10-23 05:08:37
【问题描述】:
我正在浏览 LocalDate API 的 java 源代码,发现这些方法缺少 throws 声明。但是 javadoc 清楚地提到该方法可能会抛出 DateTimeException。以下是来自 Java 8 的 LocalDate API 的源代码。
/**
* 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);
}
- 这是否是声明抛出异常的方法的正确方法(我希望 throws 在方法签名中使客户端能够正确处理异常,但这并没有给客户端关于除非正在读取 javadoc,否则异常)?
如果我遗漏了什么以正确理解这一点,请告诉我?
【问题讨论】:
-
DateTimeException是RuntimeException,不需要抛出。总是喜欢未经检查的异常,以便您仅在需要时处理它 -
对于未经检查的异常,最好不要在
throws子句中声明它们,而是在 Javadoc/API 文档中记录它们。
标签: java java-8 exception-handling localdate