[英]Should I make this a checked or unchecked exception?
我程序的一部分會檢查具有指定日期的當前數據,以查看是否在該日期之前。 如果是,我想拋出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);
}
檢查異常應該用於那些合理歇着 可預見的 ,但不可預防的錯誤。
我的問題是在我的情況下,由於我的程序需要在指定日期的28天內運行,因此該錯誤將被認為是可預測的,但無法預防,但無法從中恢復(這是因為我使用的API的限制是為了獲取事件的數據,必須在事件開始前的4周內)。 本質上,如果發生此錯誤,我有意希望該程序無法運行。
我應該將其設置為檢查異常還是非檢查異常 ,請記住,如果不滿足日期限制,則程序不應運行?
如果這是不應該發生的,而您只是想以防萬一,那么它應該是RuntimeException。 否則,檢查(預期)異常。
在此示例中,您根本不應該使用Exception。
使用if語句可以輕松實現示例中的流控制。
您的報價與上下文無關。 吉莉(Gili)解釋了他的意思是可預測的和不可預防的,但這不適用於您的情況。
:調用者會盡其所能來驗證輸入參數,但是他們無法控制的某些情況導致操作失敗。
更新
由於OP更改了代碼,因此在檢查異常和運行時異常之間似乎更具爭議性。
但是要記住有效Java中的一個規則,即當您在檢查異常和運行時異常之間做出決定時,總是問自己一個問題:您希望調用者做什么? 除了忽略或記錄異常並退出之外,他還能做得更好嗎?
您的新代碼看起來完全像這樣,因此,如果您無法將代碼更改為使用if語句,則應使用Runtime Exception而不是Checked。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.