java中try-catch-finally返回值问题

1 使用规则

  1. 如果finally块中有return语句,则try或catch中的return语句被忽略。

    finally块中应该避免使用return语句,因为finally块中如果使用return语句,会显示的消化掉try、catch块中的异常信息,屏蔽了错误的发生。

  2. 如果仅try/catch语句有return语句,则返回try/catch中变量此时对应的值,此后对变量做任何的修改,都不影响try中return的返回值。

    尽量在try/catch中使用return语句,通过finally块中达到对try或者catch返回值修改是不可行的。

  3. 如果finally块中抛出异常,则整个try、catch、finally块中抛出异常。

    finally块中避免再次抛出异常,否则整个包含try语句块的方法回抛出异常,并且会消化掉try、catch块中的异常。

    2 代码示例

public class Demo1 {
    public static void main(String[] args) {
        System.out.println(fun1());// try
        System.out.println(fun2());// catch
        System.out.println(fun3());// finally
        System.out.println(fun4());// finally
    }

    // 仅try有return语句,返回try中元素值
    public static String fun1() {
        String str = null;
        try {
            str = "try";
            return str;
        } catch (Exception e){
            str = "catch";
            return str;
        } finally {
            str = "finally";
        }
    }

    // 仅catch有return语句,返回catch中元素值
    public static String fun2() {
        String str = null;
        try {
            str = "try";
            throw new Exception();
        } catch (Exception e){
            str = "catch";
            return str;
        } finally {
            str = "finally";
        }
    }

    // finally中有return,try/catch中的return被忽略
    @SuppressWarnings("finally")
    public static String fun3() {
        String str = null;
        try {
            str = "try";
            return str;
        } catch (Exception e) {
            str = "catch";
            return str;
        } finally {
            str = "finally";
            return str;
        }
    }
    @SuppressWarnings("finally")
    public static String fun4() {
        String str = null;
        try {
            str = "try";
            throw new Exception();
        } catch (Exception e) {
            str = "catch";
            return str;
        } finally {
            str = "finally";
            return str;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值