Java:try与finally

本文通过三个示例详细解析了Java中try、catch、finally语句块中的return语句行为,尤其是在finally块中return语句的特殊处理方式,并展示了基本类型、引用类型以及类成员变量在这些语句块中的表现。

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

任何调用try 或者catch中的return语句之前,都会先执行finally语句,当然前提是finally存在。如果finally中有return语句,那么程序就return了,所以finally中的return是一定会被return的,编译器把finally中的return实现为一个warning。

例一

package exercise;
/**
 * 基本类型测试try,finally
 * @author Administrator
 *
*/
public class TestReturnAndFinally {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(new TestReturnAndFinally().test());;
    }

    static int test() {
        int x = 1;
        try {
            return x;
        }
        finally {
            ++x;
        }
    }
}

结果:
1

例二

package exercise;
/**
 * 引用类型测试try,finally
 * @author Administrator
 *
*/
public class TestReturnAndFinally3 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(new TestReturnAndFinally3().test());;
    }

    static StringBuffer test() {
        StringBuffer a = new StringBuffer("init");

        try {
            a.append(" try");
            return a;
        }
        finally {
            a.append(" finally");
        }
    }
}

结果:
init try finally

例三

package exercise;

/**
 * 普通类
 * @author Administrator
 *
*/
public class Quote {
public int a = 1;
}




package exercise;
/**
 * 引用类型中的基本类型测试try,finally
 * @author Administrator
 *
*/
public class TestReturnAndFinally2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(new TestReturnAndFinally2().test().a);;
    }

    static Quote test() {
        Quote q = new Quote();

        try {
            return q;
        }
        finally {
            q.a++;
        }
    }
}

结果:
2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值