finally return时详解

finally return时详解

具体如下代码:

package com.example.demo.java;

import java.util.ArrayList;
import java.util.List;

/**
 * Finally 详解
 * finally 都是和try catch 配合使用的,代表
 * 无论 try catch中的代码是否执行,抛出异常,
 * finally中的代码一定执行
 */
public class FinallyTest {
    private static int  a =10;
    private static List<Integer> intList = new ArrayList<Integer>();

    public static void main(String[] args) {
        System.out.println("finallyTest1:" +finallyTest1());//执行结果返回13
        System.out.println("finallyTest2:" +finallyTest2());//执行结果返回12
        System.out.println("finallyTest3:" +finallyTest3());//执行结果返回11
        System.out.println("finallyTest4:" +finallyTest4().get(0));//执行结果返回20

    }
    /**
     * 即便抛出异常,finally 里的代码依然要执行
     * @return
     */
    public static int finallyTest1(){
        try{
            a = 11;
            throw new Exception();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            a=13;
            return a;
        }

    }
    /**
     * 如果finally 中也有return ,会将try catch 中的值覆盖调
     * @return
     */
    public static int finallyTest2(){
        try{
            a = 11;
            return a;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return a =12;
        }
    }

    /**
     * finally 里没有return,但是改变了返回值,这时不会覆盖
     * @return
     */
    public static int finallyTest3(){
        try{
            a = 11;
            return a;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            a =14;
        }
        return a;
    }

    /**
     * finally 里没有return,返回的是引用类型,这时引用类型的值会改变
     * @return
     */
    public static List<Integer> finallyTest4(){
        try{
            a = 11;
            intList.add(a);
            return intList;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            intList.set(0,20);
        }
        return intList;
    }
}

结果如截图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

*勇往直前*

带你装逼带你飞

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值