【发布时间】:2020-08-11 22:37:10
【问题描述】:
我正在为一些验证用户出生日期的遗留代码编写一些测试。我在课堂上遇到以下方法。我的疑问是 try 块中的 if 语句是否是必要的。据我了解,如果 parse 函数成功返回一个 LocalDate 对象,那么 date.toString() 应该总是等于输入的 dobstr,不需要做额外的检查。我错过了什么吗?我想不出我们需要这种额外检查的任何情况。请帮忙。谢谢!
private LocalDate format(String dobStr) throws Exception {
LocalDate date = null;
try {
date = LocalDate.parse(dobStr, DateTimeFormatter.ISO_DATE);
if (!dobStr.equals(date.toString())) {
throw new DateTimeParseException("some message");
}
}
catch (DateTimeParseException ex) {
throw ex;
}
return date;
}
这是我在 DateTimeFormatter.ISO_DATE 的源代码中找到的
public static final DateTimeFormatter ISO_DATE;
static {
ISO_DATE = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_DATE)
.optionalStart()
.appendOffsetId()
.toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
}
【问题讨论】:
标签: java exception localdate isodate defensive-programming