【问题标题】:How to set up a try/catch for an integer entered如何为输入的整数设置 try/catch
【发布时间】:2014-04-01 23:02:24
【问题描述】:

我想知道如何在一个字符串变量上设置 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 还必须能够处理字符并保持程序运行。

【问题讨论】:

  • 为什么要抛出异常,如果你在同一个块中捕获它?您可以使用简单的 ifs 而不必为整个异常处理而烦恼。在 Integer.parseInt() 方法上使用它,它实际上做了一些事情。

标签: java char integer try-catch


【解决方案1】:

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
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多