finally块中的代码什么时候被执行

本文详细探讨finally块在Java异常处理中的作用,强调其无论异常发生与否都会被执行,并通过实例解析return语句对finally块的影响,以及finally中return语句对函数返回值的影响。
摘要由CSDN通过智能技术生成

finally块中的代码什么时候被执行

1.finally块的作用
在Java语言的异常处理中,finally块的作用就是为了保证无论出现什么情况,finally块里的代码块一定会被执行。由于程序执行return就意味着结束对当前函数的调用并跳出这个函数体,所以任何语句要执行都只能在return前执行(除非碰到exit函数)。


例一
public class Test{
	public static int testFibally(){
		try{
			return 1;
		}catch(Exception e){
			return 0;
		}finally{
			System.out.println("execute finally");
		}
	}
	public static void main(String[] args){
		int result = testFinally();
		System.out.println(result);
	}
}

运行结果:

execute finally
1

从上面的例子可以看出在执行retrun语句前确实执行了finally块中的代码。

例二
public class Test{
	public static int testFibally(){
		try{
			return 1;
		}catch(Exception e){
			return 0;
		}finally{
			System.out.println("execute finally");
            return 3;
		}
	}
	public static void main(String[] args){
		int result = testFinally();
		System.out.println(result);
	}
}

运行结果:

execute finally
3

当finally块中有return语句时,将会覆盖函数中其他return语句。

例三
import java.sql.SQLOutput;

public class Test {

    public  static int testFinally(){
        int result = 1;
        try{
            result = 2;
            return result;
        }catch(Exception e){
            return 0;
        }finally{
            result = 3;
            System.out.println("execute finally1");
        }
    }
    public static StringBuffer testFinally2(){
        StringBuffer s = new StringBuffer("Hello");
        try{
            return s;
        }catch (Exception e){
            return null;
        }finally {
            s.append(" World");
            System.out.println("execute finally2");
        }
    }
    public static void main(String[] args){
        int resultVal = testFinally();
        System.out.println(resultVal);
        StringBuffer resultRef = testFinally2();
        System.out.println(resultRef);
    }
}

运行结果:

execute finally1
2
execute finally2
Hello World

程序在执行到return语句时首先将返回值存储在一个指定的位置,其次去执行finally块,最后再返回。此时修改result的值将不会影响到程序的返回结果。(finally块里的内容仍然会被执行,如Hello World的输出,此时的s为引用类型)。

新手上传
如有错误,欢迎指出ヾ(≧▽≦*)o
from《java程序员面试笔试宝典》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值