try-catch-finally块的执行流程

记得前些天看try-catch-finally的东西,在很多博客上看了很多文章,也没有理解的很透彻,今天看到了国外的一个牛人讲的,感觉非常好非常透彻,完全没有云里雾里的感觉,就把它翻译过来。

在这篇文中我们来看一下怎么使用try-catch-finally块来进行异常处理,在看这个之前可以先看一下try-catch

try-catch块的流程控制

当异常不发生的时候:

当在try块中的语句没有抛出异常的时候,catch永远不会被执行。

例如:

 

.....
int x = 10;
int y = 10;
try{
   int num= x/y;
   System.out.println("next-statement: Inside try block");
}catch(Exception ex)
 {
    System.out.println("Exception");
 }
System.out.println("next-statement: Outside of try-catch");
...


输出结果:

 

 

next-statement: Inside try block
next-statement: Outside of try-catch


上边的例子中没有异常发生,所以catch没有执行

 

当异常发生的情况:

 

int x = 0;
int y = 10;
try{
   int num= y/x;
   System.out.println("next-statement: Inside try block");
}catch(Exception ex)
 {
    System.out.println("Exception Occurred");
 }
System.out.println("next-statement: Outside of try-catch");
...


输出结果:

 

 

Exception Occurred
next-statement: Outside of try-catch


在上边的例子中,有两条语句在try块中,因为异常发生在第一条语句中,所以第二条语句没有被执行,因此我们可以总结:一旦异常发生try块中剩下的语句不会被执行同时执行控制也被传递到catch块中。

 

try/catch/finally块的流程控制:

1、如果在try块中发生异常那么控制会立刻被传递(跳过try块中的剩下的其他语句)到catch中去。一旦catch块执行完成之后finally块和其后的程序执行

2、如果在代码中没有异常发生,try块中的代码会被完全执行,然后执行控制被传递到(跳过catch块)finally块中

3、如果在catch或者try块中有return语句,在这种情况下,finally也会执行,控制流是:先执行finally然后回到return语句。

考虑下边的代码理解上边的观点:

 

class TestExceptions {
   static void myMethod(int testnum) throws Exception {
      System.out.println ("start - myMethod");
      if (testnum == 12) 
         throw new Exception();
      System.out.println("end - myMethod");
      return;	
   }
   public static void main(String  args[]) {
      int testnum = 12;
      try {
         System.out.println("try - first statement");
         myMethod(testnum);
         System.out.println("try - last statement");
      }
      catch ( Exception ex) {
         System.out.println("An Exception");
      }
      finally {
         System. out. println( "finally") ;
      }
      System.out.println("Out of try/catch/finally - statement");
   }
}


输出结果:

 

 

try - first statement
start - myMethod
An Exception
finally
Out of try/catch/finally - statement

 

关于return和finally谁先返回的问题,请看这篇文章,点击

原文地址:http://beginnersbook.com/2013/05/flow-in-try-catch-finally/

关注我,获取400个的赚钱金点子,轻松开启程序员的副业生涯

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值