为什么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,提问作者Валентин Д.
相关产品推荐
相关产品推荐

