欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

try、catch、finally的执行顺序

发布时间:2024/7/19 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 try、catch、finally的执行顺序 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

 

有这样一段代码 :

public class EmbededFinally {

     public static void main(String args[]){

          int result;

          try {

               System.out.println("in Level 1");

 

               try {

                    System.out.println("in Level 2");

  // result=100/0;  //Level 2

                    try {

                         System.out.println("in Level 3");

                            result=100/0;  //Level 3

                    }

                    catch (Exception e) {

                         System.out.println("Level 3:" + e.getClass().toString());

                    }

                                    finally {

                         System.out.println("In Level 3 finally");

                    }

                                   // result=100/0;  //Level 2

                }

               catch (Exception e) {

                    System.out.println("Level 2:" + e.getClass().toString());

               }

    finally {

                    System.out.println("In Level 2 finally");

               }

                // result = 100 / 0;  //level 1

          }

          catch (Exception e) {

               System.out.println("Level 1:" + e.getClass().toString());

          }

          finally {

               System.out.println("In Level 1 finally");

          }

     }

当我去掉level2中level3前面的注释时,level3的catch不再执行;

当我去掉level2中level3后面的注释时,level3的catch执行;

所以得到,当try中发现异常并抛出异常之后则不向下执行,直接转到catch接收异常,最后执行同层次finally。

}

转载于:https://www.cnblogs.com/hehejeson/articles/4963852.html

总结

以上是生活随笔为你收集整理的try、catch、finally的执行顺序的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。