异常 -- 自己的理解

it2022-05-09  30

(1)使用 try-catch 显示地捕获异常时,当 try 代码块中的某一行代码出现异常时,则 try 代码块中该行以后的代码都无法执行,        异常被 catch 块捕获后,则之后的代码都将可以被执行到,所以 try-catch 的目的是保证程序在异常的情况下执行完毕,同时会告知

    程序员出错的异常信息,如:

     public static void testException1() {     int[] ints = new int[] { 1, 2, 3, 4 };     System.out.println("异常出现前");     try {         System.out.println(ints[4]);         System.out.println("我还有幸执行到吗");// 发生异常以后,该行代码不能被执行     } catch (IndexOutOfBoundsException e) {      // 可以得到执行        System.out.println("数组越界错误");  // 可以得到执行     }    System.out.println("异常出现后");          // 可以得到执行    }  (2)如果不使用 try-catch 捕获异常,则可能导致有些代码不能被得到执行,如:

      public static void testException2() {        int[] ints = new int[] { 1, 2, 3, 4 };        System.out.println("异常出现前");        System.out.println(ints[4]);           //发生了异常        System.out.println("我还有幸执行到吗");// 发生异常以后,他后面的代码不能被执行      }

转载于:https://www.cnblogs.com/jennyWangBlogs/p/8422565.html


最新回复(0)