您的位置:首页 > 编程语言 > Java开发

java中try、catch、finally返回语句执行顺序

2016-09-05 22:08 459 查看
(1)如果catch块中有返回语句,则先执行finally语句块中的代码。

public class Main {

public static void main(String[] args) {
System.out.println(test());
}

public static String test(){
try{
int i=10/0;
}catch(Exception e){
return "catch";
}finally{
System.out.println("finally");
}
return null;
}
}

输出结果:

finally

catch

(2)如果catch块和finally块中均有返回语句,则finally块中的返回语句会覆盖catch块中的返回语句,即catch块执行到return语句之前会执行finally块中的代码。

public static String test(){
            try{
                int i=10/0;
            }catch(Exception e){
                return "catch";
            }finally{
                return "finally";
            }
        }
输出结果:
finally

(3)如果catch块中有System.exit(0)语句,则直接退出程序。

public static String test(){
        try{
            int i=10/0;
        }catch(Exception e){
            System.out.println("exit之前");
            System.exit(0);
            System.out.println("exit之后");
            return "catch";
        }finally{
            return "finally";
        }

输出结果:

exit之前
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  exception