JavaSE: finally的使用

finally通常用于进行善后处理,如:关闭已经打开的文件等

 

示例:

 

  class ExceptionFinallyTest{

    public static int test() {

      try{

        int[] arr = new int[5];

        print(arr[5]); 

        return 0; 

      } catch(ArrayIndexOutofBoundException e) {

        e.printStackTrace();

        return 1;

      } finally {

        return 2;

      }

    } // test()方法最终的返回值为 2 

    main(String[] args){

      try{

        int ia = 10;

        int ib = 1;

        print (ia / ib);

      } catch(ArithmeticException e){

        e.printStackTrace();

        String srt1 = null;

        str1.length(); // 会发生空指针异常,但是finally仍然会执行

      } finally{

        print("无论是否发生异常,都记得来执行我哦!"); // 依然是执行

      }

 

      print("over"); // 不执行了

    }

  }

 

执行流程:

  try{

    a;

    b:  可能发生异常的语句

    c;

  } catch (Exception e){

    d;

  }finally{

    e;

  }

 

  当没有发生异常时的执行流程: a  b  c  e

  当发生异常时的执行流程: a  b  d  e

posted @ 2021-06-07 16:28  Jasper2003  阅读(51)  评论(0)    收藏  举报