finally{}语句面试知识点总结

本文详细介绍了Java中finally语句的执行特性,无论异常是否发生,finally块总会执行。通过案例分析了在return语句存在时,finally如何影响方法返回值,特别是对于基本数据类型和引用数据类型的差异。最后,讨论了finally在方法返回值为引用类型时如何改变返回对象的状态,以及在非引用类型时不影响返回值的情况。
摘要由CSDN通过智能技术生成

finally{}语句面试知识点总结

无论 try、catch语句中异常是否发生,除非电脑断电或程序不在内存中,finally语句必然执行。
案例一:
当test方法中的return语句执行后方法结束,finally语句还会不会执行

public class FinallyDemo {
    public static void main(String[] args) {
        test();
        }
    public static void test(){
        try{
            System.out.println("1");
            return;
        }catch(Exception e){

        }finally{
            System.out.println("finally语句已执行");
        }
    }
}


执行结果:

Connected to the target VM, address: '127.0.0.1:55869', transport: 'socket'
1
finally语句已执行
Disconnected from the target VM, address: '127.0.0.1:55869', transport: 'socket'

Process finished with exit code 0

原因:
finally的执行时间实际上是在return a语句的中间; test方法在准备return方法的返回结果时finally语句被执行。

特殊案例:
注意方法返回值为基本数据类型与引用数据类型之间的区别

引用类型:

public class FinallyDemo {
    public static void main(String[] args) {
        Persion p = test();
        System.out.println(p.age);
    }

    public static Persion test() {
        Persion p = new Persion();
        try {
            p.age = 18;
            return p;
        } catch (Exception e) {
            return p;
        } finally {
            p.age = 28;
        }
    }
        static class Persion {
            int age;
        }


    }

执行结果:

Connected to the target VM, address: '127.0.0.1:56264', transport: 'socket'
28
Disconnected from the target VM, address: '127.0.0.1:56264', transport: 'socket'

Process finished with exit code 0

非引用类型:

public class FinallyDemo {
    public static void main(String[] args) {
        int a = test();
        System.out.println(a);
    }

    public static int test() {
        try {
            int a= 10;
            return a;
        } catch (Exception e) {
            return 0;
        } finally {
            int a= 20;
            System.out.println("finally语句已执行");
        }
    }
    }

结果:

Connected to the target VM, address: '127.0.0.1:56644', transport: 'socket'
finally语句已执行
10
Disconnected from the target VM, address: '127.0.0.1:56644', transport: 'socket'

Process finished with exit code 0
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值