如何为输入的整数设置 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 还必须能够处理字符并保持程序静止运行。

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
 }

相关内容

  • 没有找到相关文章

最新更新