为何此Java代码中的NumberFormatException未被捕获?
Java异常处理疑问
public class Test { public static int temp(String a, String b) { try { System.out.print("A"); return Integer.parseInt(a)/Integer.parseInt(b); } catch(ArithmeticException e) { System.out.print("C"); return 0; } finally { System.out.print("D"); return -1; } } public static void main(String[] args) { try { System.out.print(temp("1", null)); } catch (Exception e) { System.out.print("E"); } finally { System.out.print("F"); } } }
- 实际程序输出:
AD-1F - 预期输出:
AD-1EF,理由:参数b为null时,Integer.parseInt(b)会抛出NumberFormatException,该异常应向上传播并被main方法中的catch块捕获 - 对比测试:将main方法try块中的代码替换为
Integer.parseInt(null),输出为EF,说明这种场景下NumberFormatException确实会被捕获
内容的提问来源于stack exchange,提问作者strugglingcsstudent
相关产品推荐
相关产品推荐

