家庭作业:为什么捕获被绕过?

时间:2014-08-21 16:02:37

标签: java try-catch

我有以下代码:

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。相反,它完全跳过捕获并转到返回日期。我哪里错了?

2 个答案:

答案 0 :(得分:2)

Catch仅在尝试的主体抛出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;             

答案 1 :(得分:1)

原因是您的 checkDate 不会抛出异常

如果你改变:

   if(dateCheck == true) {
        return date;
   }           

   if(dateCheck == false) {
        throw new IllegalArgumentException("Check did not pass");
   } 

你可以为他扔一个,它应该按照你的预期工作。