try catch finally解惑

try catch finally解惑

Finally通常会配合try、catch使用,在try。。。catch没有退出的语句(return 或者是抛出异常导致退出try。。。catch)执行完try。。。catch语句后,再来执行finally;另外一种情况是在try。。。catch有退出的语句,在每一处的try或catch将要退出该方法之前,JVM都会保证先去调用finally的代码,这里所说的退出不单单是指return语句,try或catch中异常的抛出也会导致相应方法的退出(当然,前提是不被catch捕获以及不被finally跳转)。在执行finally代码时,如果finally代码本身没有退出的语句(return或抛出异常),finally执行完毕(除了finally中有return语句)后还会返回try或catch之前要退出的地方,由try或catch执行退出指令。

static intf4() { 

            try

                throw new Exception("try error "); 

            } catch (Exception e) { 

               System.out.print("throw excetion ");

                throw new RuntimeException("catch error "); 

            } finally

                System.out.print("f4"); 

                Return 0

            } 

结果:throw excetion f4 : 0

在通过外面的程序调用这个函数

try

            System.out.println(" : " + f4()); 

        } catch (Exception e) { 

            System.out.println(" : " + e.getMessage()); 

  } 

在上面程序中先抛出throw new Exception("try error"异常,同时被catch到然后执行

System.out.print("throw excetion");

当执行到throw new RuntimeException("catcherror");  时,编译器知道这是退出的意识(还包括return 语句等),此时由于finally具有在try或catch将要退出(包括return 以及抛出异常)该方法之前,JVM都会保证先去调用finally的代码,此时执行finally中的代码

System.out.print("f4"); 

Return 0

此时该函数f4()并没有向外抛射异常

同样的道理

static int f4() { 

            try

                throw new Exception("try error "); 

            } catch (Exception e) { 

             System.out.print("throw excetion ");

                 return 1;

            } finally

                System.out.print("f4"); 

                return 0;

            } 

         

       } 

此时结果

throwexcetion f4 : 0

static int f4() { 

            try

             System.out.print("try ");

                 return 2;

            } catch (Exception e) { 

             System.out.print("throw excetion ");

                 return 1;

            } finally

                System.out.print("f4"); 

                return 0;

            }  

         

       } 

结果try f4 : 0

还有就是执行完try。。。catch(此时没有退出的语句)在执行完try。。。catch的语句后,再来执行finally如:

static int f4() { 

            try

             System.out.print("try ");

               

            } catch (Exception e) { 

             System.out.print("throw excetion ");

               

            } finally

                System.out.print("f4"); 

                return 0;

            } 

         

       } 

结果try f4 : 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值