黑马程序员技术交流社区

标题: 论坛中有位大神提用了如下代码,但是finally语句中,不能... [打印本页]

作者: 李永佳    时间: 2015-5-13 17:48
标题: 论坛中有位大神提用了如下代码,但是finally语句中,不能...
论坛中有位大神提用了如下代码,但是finally语句中,不能加入return语句,他这段代码是不是正确的

package com.itheima;

/**
* 5、 用代码证明,在try中写了return,后面又写了finally,是先执行return还是先执行fianlly?
*/

public class Test5 {
                public static void main(String[] args){
                        System.out.println(test());
                }
                //自定义一个test测试函数
                public static boolean test(){
                        try{
                                //用来检测try块里面处于return前的语句是否有被执行
                                System.out.println("try语句块被执行");
                                return false;
                        }
                        finally{       
                                //用来检测finally语句块中的语句有没有被执行
                                System.out.println("finally语句块被执行");
                                return true;
                        }               
                }
//                先执行try 语句

}



作者: pvbj0314    时间: 2015-5-13 20:06
本帖最后由 pvbj0314 于 2015-5-13 20:08 编辑

"The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated." -- finally Block: https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
文中红色部分就是答案。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2