zoukankan      html  css  js  c++  java
  • 抛出异常

    下面的程序输出如何?

     1 public class Test {
     2 
     3     public static void main(String[] args) {
     4         System.out.println(getResult());
     5     }
     6 
     7     public static int getResult() {
     8         
     9         try{
    10             try{
    11                 throw new RuntimeException("exception");    
    12             }catch(RuntimeException re){
    13                 
    14             }
    15             return 1;
    16         }catch(Exception e){
    17             return 2;
    18         }finally{
    19             return 3;
    20         }
    21         
    22     }
    23 
    24 }

    运行的输出为 3

    究其原因,猜测是这样的:内部的try中执行抛出RuntimeException后,不再运行 return 1

    然后来到外部的try代码块,可以说它抛出异常了也可以说它是正常运行了,然而无论如何,此try块最终都会执行对应的finally块

    而反过来讲,既然执行了return 3,那么说明此try块是正常运行的,否则其抛出异常,便return 2,程序便结束了。

    总的来说,整个程序运行的流程是这样的:

    首先运行里面的代码块抛出异常,而一旦抛出异常后,后面的程序便不能运行,因此不会return 1

    接着看外部的try块,内部的try块正常执行,因此不会return 2

    最后执行外部try块对应的finally块,return 3

  • 相关阅读:
    数组的基本操作
    面向对象
    继承
    JavaBean规范
    JVM内存模型
    数组的排序
    this
    访问控制权限
    数组
    方法的重载
  • 原文地址:https://www.cnblogs.com/Hyacinth-Yuan/p/9684911.html
Copyright © 2011-2022 走看看