try catch finally 用法

来源:blog.csdn.net 更新时间:2023-05-25 21:55
在分析此问题之前先看看它们的介绍:

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

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

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

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

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

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

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

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

正常情况下,先执行try里面的代码,捕获到异常后执行catch中的代码,最后执行finally中代码,
当try或catch中有return语句时,先执行try或catch语句块中return前面的代码,在执行finally语句中的代码,之后在返回。所以try或catch中有return也照样会执行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.

 

上一篇:&&的优先级 下一篇:返回列表