You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Java中输入非整数时,catch块无法捕获NumberFormatException?

问题原因

你调用Integer.parseInt()转换输入内容的代码写在了try代码块的外部,当用户输入非整数字符串时,NumberFormatException会在进入try块之前就抛出,自然不会被后面的catch语句捕获。

修正方案

把Integer.parseInt()语句移动到try块内部即可,优化后的参考代码如下:

String inputStr = JOptionPane.showInputDialog("Donnez une note");
String s;
try {
    // 把转换逻辑移到try块内
    int input = Integer.parseInt(inputStr);
    for (int i = 0; i < prs.size(); i++) {
        s = prs.get(i).toString();
        if (s.contains(String.valueOf(input))) {
            filterStudents.add(prs.get(i));
        }
    }

    if (!filterStudents.isEmpty()) {
        JOptionPane.showMessageDialog(null,
                "C'est les etudiants qui ont note: " + input + "\n" + filterStudents);
    } else
        JOptionPane.showMessageDialog(null, "Il n'y a pas des etudiants avec note " + input);
    filterStudents.clear();
} catch (NumberFormatException e) {
    // 可以针对输入非整数的情况做专门提示
    JOptionPane.showMessageDialog(null, "请输入合法的整数!");
} catch (Exception ex) {
    JOptionPane.showMessageDialog(null, "An Error Occured!");
}

补充优化建议

  • 可以新增对inputStr的空值判断,处理用户点击输入框取消按钮返回null的边界情况
  • 优先捕获具体的NumberFormatException类型,再捕获通用Exception,可以针对不同异常给出更精准的提示,提升用户体验

内容的提问来源于stack exchange,提问作者Валентин Д.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 10:57:00