gpt4 book ai didi

java - 在 Java 中使用嵌套的 try 语句

转载 作者:行者123 更新时间:2023-11-29 03:49:17 24 4
gpt4 key购买 nike

我对 java 中的嵌套 try 语句有一些问题,我被要求使用 try 嵌套语句而不是 if()

这是我需要使用嵌套 try 语句的部分代码

 public Date subtractYear() throws Exception
{
if (day == 29 && month == 2)
return new Date(28, month, year - 1);
else
return new Date(day, month, year - 1);
}

最佳答案

上面的代码往好了说是错误的,往坏了说是危险的。 DateCalendar 类的存在是有原因的。管理闰年就是其中之一。

上面的代码应该只在你真正理解你在做什么并且需要通过这种方式实现性能的情况下才能看到生产。您最好的选择如下:

public Date subtractYear() {
final Calendar c = new Calendar();
c.set(year, month, day); // set your class's "current" date
c.add(Calendar.YEAR, -1); // remove 1 year
return c.getTime(); // get the Date object back from the Calendar
}

作为补充说明,使用 try-catch block 来处理正常的程序流通常不是处理您通常期望的事情的好方法。异常堆栈跟踪的生成是一项代价高昂的操作。

关于java - 在 Java 中使用嵌套的 try 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9502830/

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