我的程序的一部分检查具有指定日期的当前数据,以查看它是否在该日期之前。如果是,我想抛出一个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 有一个限制为了获取事件的数据,它必须在事件开始前的 4 周内)。本质上,如果发生此错误,我故意希望程序无法运行。我应该将此设置为已检查异常还是未检查异常,请记住,如果不满足日期限制,程序不应运行?
添加回答
举报
0/150
提交
取消