try、catch、finally中return的执行顺序

                                                                  try、catch、finally中的return

       今天在做一个多线程加读写锁的测试时,考虑效率问题,想及时return结果,但存在一个严肃的问题,那就是锁的开启和关闭问题。因为锁开启后,用完不及时关闭,会因堵塞而造成资源无法请求。因此,做了一个测试,尽量做到全面,哪怕有些显得有些脑残,测试嘛。

示例1.

/**
 * @author qing
 * 
 *    Try……catch……finally中return的测试
 */
public class TryTest {
 
    /**
     * 主要方法
     */
    public static void main(String[] args) {
        // 调用 测试方法
        String result = get();
        // 打印 测试方法返回的结果
        System.out.println(result);
    }
 
    @SuppressWarnings({ "finally", "unused" })
    public static String get(){
        int value = 0;
        try {
            System.out.println("try……");
            
            //等式1/0 :分母为0 的明显错误          ——制造错误(用于抛异常)
            int result = 1 / value;
            
            return "111";
            
        } catch (Exception e) {
            System.out.println("catch……");
            return "444";
        } finally {
            System.out.println("finally……");
            return "333";
        }
        
//        return "222";
    }
运行结果:


经过测试:

(1)在通过编译器的检查后,如果finally中有return,则以finally中的return为准,其他的都将失效,return之前的代码都有效。

(2)第37行的return “222” 于catch、finally中的任何一个return互斥。也就是说,在catch、finally中其中一个地方存在return,编译器就能检查,已符合方法的返回要求。

(3)catch和finally中,可同时存在return,编译能通过。但程序以finally中的return “333”为准,不会理睬catch中的return “444”,catch中return之前的代码仍然生效。

示例2.     (这种情况就比较好理解了)

         程序中try内部没有异常的情况下,若有finally,且finally中没有return。若在try中遇到return,则先跳去执行finally中的代码,在回来执行try中return。

package threadproject;
 
/**
 * @author qing
 * 
 *    Try……catch……finally中return的测试
 */
public class TryTest {
 
    /**
     * 主要方法
     */
    public static void main(String[] args) {
        // 调用 测试方法
        String result = get();
        // 打印 测试方法返回的结果
        System.out.println(result);
    }
 
    public static String get(){
        try {
            System.out.println("try……");
            
            return "111";
            
        } catch (Exception e) {
            System.out.println("catch……");
        } finally {
            System.out.println("finally……");
        }
        
        return "222";
    }
 
}
运行结果为:


上面的程序不会执行  try……Catch……finally之外的return,即打印的是“111”,而不打印“222”。
———————————————

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值