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

为何此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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:51:59