菜鸟笔记
提升您的技术认知

try catch finally 用法

在讲之前我们先看一段程序:

public class Test {
    public static void main(String[] args) {
        System.out.println("return value of getValue(): " +
        getValue());
    }
	public static int getValue() {
         try {
             return 0;
         } finally {
             return 1;
         }
     }
 }

请问答案是:“return value of getValue():0 还是  return value of getValue():1”呢?

在分析此问题之前先看看它们的介绍:

try catch finally 是java中的异常处理的常用标识符,常用的组合为:

1.
try {
    //逻辑代码
   }catch(exception e){
    //异常处理代码
} finally{
    //一定要执行的代码
}

2.
try {
   //逻辑代码
   }catch(exception e){
   //异常处理代码
}

3.
try{
   //逻辑代码
}finally{
   //一定要执行的代码
}

try { //执行的代码,其中可能有异常。一旦发现异常,则立即跳到catch执行。否则不会执行catch里面的内容 } 

catch { //除非try里面执行代码发生了异常,否则这里的代码不会执行 } 

finally { //不管什么情况都会执行,包括try catch 里面用了return ,可以理解为只要执行了try或者catch,就一定会执行 finally }

 其实这些都还好理解,主要就是finally中的代码执行顺序的问题,这里给出我的想法:

       正常情况下,先执行try里面的代码,捕获到异常后执行catch中的代码,最后执行finally中代码,但当在try catch中执行到return时,要判断finally中的代码是否执行,如果没有,应先执行finally中代码再返回。

例如某些操作,如关闭数据库等。

为了证实我的猜想,我们来看几个例子:

代码1:

public class Test {
    public static void main(String[] args) {
        System.out.println("return value of getValue(): " +
        getValue());
    }
	public static int getValue() {
         try {
        	 System.out.println("try...");
        	 throw new Exception();
         } catch(Exception e){
        	 System.out.println("catch...");
        	 return 0;
         }finally {
        	 System.out.println("finally...");
             return 1;
         }
     }
 }

 运行结果:

try...
catch...
finally...
return value of getValue(): 1

 代码2:(将return 1 注释)

public class Test {
    public static void main(String[] args) {
        System.out.println("return value of getValue(): " +
        getValue());
    }
	public static int getValue() {
         try {
        	 System.out.println("try...");
        	 throw new Exception();
         } catch(Exception e){
        	 System.out.println("catch...");
        	 return 0;
         }finally {
        	 System.out.println("finally...");
             //return 1;
         }
     }
 }

运行结果:

try...
catch...
finally...
return value of getValue(): 0

意思就是在try 和catch中如果要return,会先去执行finally中的内容再返回

讲到这里,前面题目的答案也就知道了,是“return value of getValue():1”。

当在try中要return的时候,判断是否有finally代码,如果有,先执行finally,所以直接return 1.