java的异常处理(二)

最后总结:finally块的语句在try或catch中的return语句执行之后返回之前执行且finally里的修改语句不能影响try或catch中return已经确定的返回值,若finally里也有return语句则覆盖try或catch中的return语句直接返回。 
如果finally语句中没有return语句覆盖返回值,那么原来的返回值就不会因为finally里的修改而改变。
  1. public class FinallyTest3 {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         System.out.println(test3());  
  6.     }  
  7.   
  8.     public static int test3() {  
  9.         int b = 20;  
  10.   
  11.         try {  
  12.             System.out.println("try block");  
  13.   
  14.             return b += 80;  
  15.         } catch (Exception e) {  
  16.   
  17.             System.out.println("catch block");  
  18.         } finally {  
  19.   
  20.             System.out.println("finally block");  
  21.   
  22.             if (b > 25) {  
  23.                 System.out.println("b>25, b = " + b);  
  24.             }  
  25.   
  26.             b = 150;  
  27.         }  
  28.   
  29.         return 2000;  
  30.     }  
  31.   
  32. }  
http://blog.csdn.net/lanxuezaipiao/article/details/16922895
try块里的return语句在异常的情况下不会被执行,这样具体返回哪个看情况。
  1. public class FinallyTest4 {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         System.out.println(test4());  
  6.     }  
  7.   
  8.     public static int test4() {  
  9.         int b = 20;  
  10.   
  11.         try {  
  12.             System.out.println("try block");  
  13.   
  14.             b = b / 0;  
  15.   
  16.             return b += 80;  
  17.         } catch (Exception e) {  
  18.   
  19.             b += 15;  
  20.             System.out.println("catch block");  
  21.         } finally {  
  22.   
  23.             System.out.println("finally block");  
  24.   
  25.             if (b > 25) {  
  26.                 System.out.println("b>25, b = " + b);  
  27.             }  
  28.   
  29.             b += 50;  
  30.         }  
  31.   
  32.         return 204;  
  33.     }  
  34.   
  35. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值