如何为输入的整数设置try / catch

时间:2014-04-01 23:02:24

标签: java char integer try-catch

我想知道如何在一个字符串变量上设置try / catch,但是必须根据这样的整数进行检查:

public static void isValidAge(String age) {
    int age2 = Integer.parseInt(age);
    try {
        if(age2 <= 0 || age2 >= 150) {
            throw new NumberFormatException();
        }
    }
    catch (NumberFormatException ex) {
        if(age2 <= 0) {
            System.err.print("Age can not be 0 or negative.");
        }
        else if (age2 >= 150) {
            System.err.print("Age can not be equal to or more than 150.");
        }
        else if (age.contains("#@$")) {
            System.err.print("You did not enter a valid age.");
        }
    }
}

try / catch还必须能够处理字符并使程序保持运行。

1 个答案:

答案 0 :(得分:3)

try-catch应该在解析尝试本身:

 int age2 = -1; //set to an invalid value
 try
 {
    age2 = Integer.parseInt(age);
 }
 catch(Exception ex)
 {
    System.out.println("Error: Could not parse age to number, exiting");
    return; //exit function
 }