gpt4 book ai didi

java - 我应该将其设为已检查或未检查的异常吗?

转载 作者:行者123 更新时间:2023-12-01 19:50:01 25 4
gpt4 key购买 nike

我的程序的一部分检查指定日期的当前数据,看看它是否早于该日期。如果是,我想抛出一个 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;
}
}

这是我的代码,用于检查日期并在必要时引发异常(假设 todaydateSpecifiedDate 对象):

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);
}

this帖子,Gili说:

Checked Exceptions should be used for predictable, but unpreventable errors that are reasonable to recover from.

我的问题是就我而言,此错误将被视为可预测但无法预防,但无法恢复,因为我的程序需要在指定日期的 28 天内运行(这是因为我使用的 API 有一项限制是,为了获取 Activity 数据,必须在 Activity 开始前 4 周内)。本质上,如果发生此错误,我故意希望程序无法运行。

我应该将其设置为已检查异常还是未检查异常,请记住,如果不满足日期限制,则程序不应运行?

最佳答案

如果这是不应该发生的事情,并且您想捕获它以防万一,那么它应该是 RuntimeException。否则,检查(预期)异常。

关于java - 我应该将其设为已检查或未检查的异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com