【问题标题】:How to catch a NumberFormatException?如何捕获 NumberFormatException?
【发布时间】:2019-03-01 20:31:39
【问题描述】:

我试图弄清楚如何在我的代码中捕获一个 numberformat 异常错误,这样如果用户在字符串中输入一个字母并且我的程序尝试将它解析为一个 int 我的程序就不会抛出一个错误而是停止并返回一个布尔值。我也试图理解,如果 try 语句有效,我希望它继续执行以下代码。

    if (counter == 3) {
        int compare;
        boolean check = true;
        String[] newip = IpAddress.split("\\.");
        if (newip.length == 4) {
            for (int index = 0; index < newip.length; index++) {
                //There should be a try statement here.
                // if the try statement fails then I'd like for it to catch
                // the numberformatexception and evaluate my boolean to 
                //false;
                //but if it passes I'd like for it to continue to execute 
                //the following code.
                    compare = Integer.parseInt(newip[index]);
                if (compare >= 0 & (compare <= 255)) {
                    check = true;
                }
                else{
                    check = false;
                }
            }
            if (check)
                return true;
            else
                return false;
        }
        else {
            check = false;
            return check;
        }
    }
    else{
        return false;
    }
}

【问题讨论】:

  • 尝试可能抛出异常的代码,在catch块中,在出错的情况下做你想做的事(在你的情况下return false
  • 请(重新)阅读您的 Java 指南,了解 try 语句是什么以及它是如何工作的。
  • @Andreas 我认为这里不需要 try-catch 块。由于输入的字符串必须是整数,他/她应该只检查是否只有数字存在。另一个故事,如果输入的值被格式化,但那是题外话
  • @LppEdd "应该只检查是否只有数字存在" 这还不够,因为即使字符串是所有数字,也可以抛出 NumberFormatException,即如果字符串超过int 的范围。
  • @LppEdd 您如何认为这不是“要求”? OP 希望程序 “不会抛出错误”。这是一个要求。除非您手动验证字符串不是超出int 范围的数字,否则确保这一点的唯一方法是捕获异常。而 that 正是提出的问题:如何捕获 numberformat 异常。

标签: java numberformatexception


【解决方案1】:

用 try/catch 包围该行:

try {
    compare = Integer.parseInt(newip[index]);
} catch (NumberFormatException e) {
    check = false;
}

然后:

if (check) {
    if (compare >= 0 & (compare <= 255)) {
        check = true;
    } else {
        check = false;
    }
} else {
    return false;
}

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

您可以使用NumberUtils from commons-lang 3.x 来检查输入是否为数字,而不是捕获 NumberFormatException。

NumberUtils.isNumber(newip[index])

但是根据文档,4.x 将弃用它,您需要使用 isCreatable

NumberUtils.isCreatable(newip[index])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多