关于Java的异常捕获

一、 关于Java异常捕获的一点笔记:

先看代码:

 1 import java.io.FileNotFoundException;
 2 public class ExceptionTest 
 3 {
 4     
 5     int f1() throws FileNotFoundException{
 6         System.out.println("f1 Executed!");
 7         throw new FileNotFoundException("aaa");
 8     }    
 9     int f2(){
10         System.out.println("before call f1");
11         try {
12             f1();
13             System.out.println("in try after call f1");
14         } catch (FileNotFoundException e) {
15             System.out.println("Exception");
16             return 3;
17         }
18 /*        finally{
19             System.out.println("finally");
20         }*/
21         System.out.println("after call f1");
22         return 0;
23     }
24     
25     public static void main(String args[]){
26         ExceptionTest test=new ExceptionTest();
27         int x=test.f2();
28         System.out.println("x="+x);
29     }
30 }

 

对于以上代码,在函数f2中调用函数f1,f1()的功能就是throw一个Exception,再没有其他功能。

通过以上测试可以得出以下几个结论:

1. 如果catch块中有return语句,则f1()抛出例外后,catch块中的return语句是可以执行的,执行完“return 3”后,函数f2()便在此处退出,第16行之后的语句不再执行。

2. 如果catch块中没有return语句(将程序第16行的“return 3”注释掉),则f1()抛出的例外被catch捕获后,会执行catch{}块中的语句。catch块中的语句执行完之后,会继续执行try-catch以外的语句(第21行及以后的语句),于是“after call f1”会被打印,并且f2()返回0。

由此可以得出,抛出例外后,只会中断try{}块中的语句,try{}块以外的语句并不受影响,即不论是否抛出例外,只要catch{}里没有return语句,try{}块之后的语句都会被执行,不管这些语句是否在finally{}块中。

3. 那么finally{}块的存在与否有无区别呢?只有一点,当catch{}中存在return语句时(第16行),程序会先执行完finally块中的语句(第19行),再执行catch块中的return——执行顺序是第15、19、16行;这时,倘若代码语句(第19行)外没有finally{}包裹,这部分代码(第19行)便得不到执行,因为在catch块中已经return了。

而当catch{}中不存在return语句时(第16行被注释掉),语句外层是否有finally{}的包裹,其效果都是一样的(即不论是否有异常抛出,都会被执行)。

posted on 2012-12-13 13:44  大油蛙  阅读(188)  评论(0编辑  收藏  举报

导航