我有以下代码:
public static String userInput(Scanner input) {
String date = "";
int year = 0;
try{
System.out.print("Please enter a date (mm/dd/yyyy): ");
date = input.next();
boolean leapYear = getLeapYear(date);
boolean dateCheck = checkDate(date,leapYear);
if(dateCheck == true) {
return date;
}
} catch(IllegalArgumentException e) {
System.out.println(year + " " + "is not a leap year");
}
return date;
}
我已通过调试验证,当我输入非闰年日期(例如 02/29/1601)时,dateCheck 为 false。我认为会发生的是,当 if 语句为 false 时,程序将继续捕获。相反,它完全跳过捕获并转到返回日期。我哪里出错了?
最佳答案
Catch 仅在 try 主体抛出 Exception
时运行(在您的示例中仅抛出 IllegalArgumentException
)。如果您希望代码始终运行,则应将其放在 finally
block 中。 -
try{
System.out.print("Please enter a date (mm/dd/yyyy): ");
date = input.next();
boolean leapYear = getLeapYear(date);
boolean dateCheck = checkDate(date,leapYear);
if(dateCheck == true) {
return date;
} else {
// what you seem to have expected.
throw new IllegalArgumentException("not a leap year");
}
} catch(IllegalArgumentException e) {
System.out.println(year + " " + "is not a leap year");
} finally {
System.out.println("This will always print.").
}
return null;
关于java - 作业: Why is catch being bypassed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25430892/