然饱饱 2024-02-05 11:34 采纳率: 50%
浏览 6
已结题

java异常捕获机制:在catch中继续抛出异常,上层调用方不会捕获异常吗?


package Exception;
 
public class exception4 {
    public exception4() {
    }
 
    boolean testEx() throws Exception {
        boolean ret = true;
        try {
            ret = testEx1();
        } catch (Exception e) {
            System.out.println("testEx, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx, finally; return value=" + ret);
            return ret;
        }
    }
 
    boolean testEx1() throws Exception {
        boolean ret = true;
        try {
            ret = testEx2();
            if (!ret) {
                return false;
            }
            System.out.println("testEx1, at the end of try");
            return ret;
        } catch (Exception e) {
            System.out.println("testEx1, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx1, finally; return value=" + ret);
            return ret;
        }
    }
 
    boolean testEx2() throws Exception {
        boolean ret = true;
        try {
            int b = 12;
            int c;
            for (int i = 2; i >= -2; i--) {
                c = b / i;
                System.out.println("i=" + i);
            }
            return true;
        } catch (Exception e) {
            System.out.println("testEx2, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx2, finally; return value=" + ret);
            return ret;
        }
    }
 
    public static void main(String[] args) {
        exception4 testException1 = new exception4();
        try {
            testException1.testEx();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这是我在学习异常这部分知识时 看到一位博主的文章中举出的例子 这段代码的输出结果是


i=2  
i=1  
testEx2, catch exception  
testEx2, finally; return value=false  
testEx1, finally; return value=false  
testEx, finally; return value=false

我的问题是testEx2方法的catch块中通过throw e;抛出了异常,为什么在testEx1方法中这个异常没有被textEx1方法中的catch块捕获并输出相应语句,这个异常去哪里了呢?帮忙解答一下疑问,感激不尽!

  • 写回答

3条回答 默认 最新

  • shandongwill 大数据领域新星创作者 2024-02-05 13:07
    关注

    因为testEx1中的这句ret = testEx2();代码有返回值,且返回值为false,所以不再往下执行

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 2月13日
  • 已采纳回答 2月5日
  • 修改了问题 2月5日
  • 创建了问题 2月5日

悬赏问题

  • ¥30 关于#微信#的问题:微信实名不绑卡 可以实现吗 有没有专家 可以解决
  • ¥15 (标签-考研|关键词-set)
  • ¥15 求修改代码,图书管理系统
  • ¥15 请问有没求偏多标签数据集yeast,reference,recreation,scene,health数据集。
  • ¥15 传感网应用开发单片机实训
  • ¥15 Delphi 关于sAlphaImageList使用问题
  • ¥15 寻找将CAJ格式文档转txt文本的方案
  • ¥15 shein测试开发会问些啥我是写java的
  • ¥15 关于#单片机#的问题:我有个课程项目设计,我想在STM32F103veTX单片机,M3主控模块上设计一个程序,在Keil uVision5(C语言)上代码该怎么编译?(嫌钱少我可以加钱,急急急)
  • ¥15 opnet仿真网络协议遇到问题