程序的一部分会检查具有指定日期的当前数据,以查看是否在该日期之前。如果是,我想抛出一个TooEarlyException
。
我的TooEarlyException
类(请注意,它目前处于选中状态,但是我试图确定是应该选中还是取消选中它):
public class TooEarlyException extends Exception {
private int dayDifference;
private String message = null;
public TooEarlyException(int dayDifference) {
this.dayDifference = dayDifference;
}
public TooEarlyException() {
super();
}
public TooEarlyException(String message) {
super(message);
this.message = message;
}
public TooEarlyException(Throwable cause) {
super(cause);
}
public int getDayDifference() {
return dayDifference;
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}
这是我的代码,用于检查日期并在必要时引发异常(假设today
和dateSpecified
是Date
对象):
public void checkDate() throws TooEarlyException{
//Do Calendar and Date stuff to get required dates
...
//If current Date is greater than 4 weeks before the event
if(today.before(dateSpecified)) {
//Get difference of dates in milliseconds
long difInMs = dateSpecified.getTime() - today.getTime();
//Convert milliseconds to days(multiply by 8,640,000^-1 ms*s*min*h*days)
int dayDifference = (int)difInMs/8640000;
//Throw exception
throw new TooEarlyException(dayDifference);
} else { //Date restriction met
//Format date Strings
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
System.out.printf("Today Date: %s%n", df.format(today));
System.out.printf("Event Date(Actual): %s%n", df.format(eventDateActual));
System.out.printf("Event Date(4 Weeks Prior): %s%n", df.format(dateSpecified));
}
}
我怎么称呼checkDate
:
try {
checkDate();
} catch(TooEarlyException e) {
System.out.printf("Need to wait %d days", e.getDayDifference());
e.printStackTrace();
System.exit(1);
}
已检查的异常应用于可预测的,但不可预防的错误应可从恢复。< / p>
我的问题是我的情况,由于我的程序需要在指定日期的28天内运行,因此该错误被认为是可预测的,但无法预防,但无法从中恢复(这是因为我使用的API具有为了获取事件数据,必须在事件开始前4周内进行限制)。本质上,如果发生此错误,我特意希望该程序无法运行。
我应该将此作为已检查的异常还是未检查的异常,请牢记如果不满足日期限制,则程序不应运行?
答案 0 :(得分:2)
如果这是不应该发生的,而您只是想以防万一,则应为RuntimeException。否则,检查(预期)异常。
答案 1 :(得分:1)
在此示例中,您根本不应该使用Exception。
使用if语句可以轻松实现示例中的流控制。
您的报价不符合上下文。吉利(Gili)解释了他所说的可预测和不可预防的含义,不适用于您的情况。
:调用方会尽其所能来验证输入参数,但某些无法控制的条件导致操作失败。
更新
由于OP更改了代码,因此在检查异常和运行时异常之间似乎更具争议性。
但是要记住有效Java 中的一条规则,即当您在检查异常和运行时异常之间做出决定时,总是问自己一个问题:您希望调用者做什么?他能做得比忽略或记录异常并退出更好吗?
您的新代码看起来完全像这样,因此,如果无法将代码更改为使用if语句,则应使用Runtime Exception,而不是Checked。