zoukankan      html  css  js  c++  java
  • Java学习之finally

    如果catch中有return语句,finally里面的语句还会执行吗?

      会执行,在return语句的中间执行

     1 public class Test{
     2         public static void main(String[] args){
     3              System.out.println(getInt());
     4         }
     5         public static int getInt(){
     6         int a = 10;
     7         try{
     8              System.out.println(1/0);
     9         }catch(Exception e){
    10             e.printStackTrace();
    11             a=10;
    12             return a;
    13         }finally{
    14             a = 100;
    15         }
    16      }
    17 }
    18     

    出现异常后,程序执行到第12句,a=10,接着执行return语句,由于有finally语句,所以跳转到finnally语句中,此时a=100,然后程序又跳转到Catch中的return语句,此时a又恢复10,所以finally中的语句会执行,在return的中间执行。

    如果将程序修改为:

     1 public class Example2 {
     2     public static void main(String[] args) throws HanderException {
     3         System.out.println(getInt());
     4     }
     5     
     6     public static int getInt(){
     7         int a = 10;
     8         try{
     9              System.out.println(1/0);
    10         }catch(Exception e){
    11             e.printStackTrace();
    12             a=10;
    13             return a;
    14         }finally{
    15             a = 100;
    16             return a;
    17         }
    19     }
    20 }

    则执行结果a的值为100,执行完finally中的语句就直接返回了

  • 相关阅读:
    数位DP
    组合
    卢卡斯Lucas&扩展卢卡斯
    [HNOI2014]道路堵塞
    [模板]三维凸包(无讲解)
    [CF526G]Spiders Evil Plan
    [CCPC2019 ONLINE]H Fishing Master
    [CCPC2019 ONLINE]E huntian oy
    [CF1037H]Security
    [CF1037F]Maximum Reduction
  • 原文地址:https://www.cnblogs.com/sunfie/p/4787477.html
Copyright © 2011-2022 走看看