java中try catch finally注意事项,finally在代码中什么时候运行

1、在java里函数抛出异常是需要在函数上定义的,除了runtimeException外

 

2、java中finally运行的位置在函数return前,其他的代码后。函数会运算完所有执行的代码,包括return里面的表达式,只是在return操作前去执行finally里面的代码。实例如下面的代码:

public class Test{ 
    public int add(int a,int b){   
         try {
             return a+b;      
         } 
        catch (Exception e) {  
            System.out.println("catch语句块");
         }
         finally{ 
             System.out.println("finally语句块");
         }
         return 0;
    } 
     public static void main(String argv[]){ 
         Test test =new Test(); 
         System.out.println("和是:"+test.add(9, 34)); 
     }
}

 运行的结果为:

finally语句块
和是:43

 

posted @ 2015-08-20 17:09  Lammy  阅读(655)  评论(1编辑  收藏  举报