我的程序的一部分檢查具有指定日期的當前數(shù)據(jù),以查看它是否在該日期之前。如果是,我想拋出一個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)); }在這篇文章中,Gili說:Checked Exceptions應該用于可預測但不可預防的錯誤,這些錯誤可以合理地從中恢復。我的問題是在我的情況下,此錯誤將被視為可預測但無法預防,但無法從中恢復,因為我的程序需要在指定日期的 28 天內運行(這是因為我使用的 API 有一個限制為了獲取事件的數(shù)據(jù),它必須在事件開始前的 4 周內)。本質上,如果發(fā)生此錯誤,我故意希望程序無法運行。我應該將此設置為已檢查異常還是未檢查異常,請記住,如果不滿足日期限制,程序不應運行?
2 回答

慕的地6264312
TA貢獻1817條經(jīng)驗 獲得超6個贊
如果這是不應該發(fā)生的事情并且您想抓住它以防萬一,那么它應該是 RuntimeException。否則,檢查(預期)異常。
添加回答
舉報
0/150
提交
取消