java异常体系---不要在finally块中使用return、throw

本文详细探讨了Java中finally块的使用方式及其对程序流程的影响,特别是在与return和throw结合使用时的情况。当finally块中包含return或throw时,编译器不再检查try或catch块中的非运行时异常,程序的输出将依据finally块的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在finally块中使用return、throw,会导致编译告警:finally block does not complete normally。

情况一:finally块中没retrun、throw

复制代码

public static void method_1() {
    try {
        System.out.println("try block run");
        throw new Exception("try block 异常");
    } finally {
        System.out.println("finally block run");
    }
}

public static void method_2() {
    try {
        System.out.println("try block run");
    } catch (Exception e) {
        System.out.println("catch block run");
        throw new Exception("catch block 异常了!");
    } finally {
        System.out.println("finally block run");
    }
}

复制代码

 说明:程序报错,Unhandled exception type Exception。此时编译器会检查try块、catch块中的非运行时异常。

情况二:finally块中有retrun或者throw

复制代码

public static void method_1() {
    try {
        System.out.println("try block run");
        throw new Exception("try block 异常");
    } finally {
        System.out.println("finally block run");
        return;
    }
}
程序运行结果:try block run   》》  finally block run

public static void method_2(){
    try{
        System.out.println("try block run");   
    }catch (Exception e) {
        System.out.println("catch block run");
        throw new Exception("catch block 异常了!");
    }finally{
        System.out.println("finally block run");
        throw new RuntimeException("finally block 异常了!");
    }    
}
程序运行结果:try block run   》》  finally block run  》》  finally block 异常了!

复制代码

说明:程序告警,finally block does not complete normally。此时编译器不会检查try块、catch块中的非运行时异常。

JVM不会再去捕获try块、catch块中的异常,而是得到(使用return时)finally块的返回值或者(使用throw时)finally块中抛出的异常。

结论:

当在finally块中使用return、throw时,编译器不会再对try、catch块中的非运行时异常进行检查,JVM不会再去捕获try块、catch块中的异常,程序的输出以finally块为准,即finally块的返回值或者finally块中抛出的异常。

当在try块或catch块中遇到return语句时,finally块将在方法返回之前被执行。finally块中的return语句会覆盖try块、catch块中的return语句。合理的做法是在 finally 块之后使用return语句。

转载于:https://my.oschina.net/u/1034481/blog/824203

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值