您的当前位置:首页正文

第三十一课:异常

来源:华佗小知识
public class Exception{

    // 下面的例子声明了一个含有两个元素的数组。然后代码试图访问数组的第三个元素,这将抛出一个异常。
    public static void main(String[] args) {
        
      try{
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);

      }catch(ArrayIndexOutOfBoundsException e){

         System.out.println("Exception thrown  :" + e);
      }

      System.out.println("Out of the block");


    /*
    finally 关键字用于创建跟在 try 后面的代码块,finally代码块总是会被执行的,不管是怎样的异常发生。

    使用 finally 块允许你运行您想要执行的任何 cleanup-type 语句,无论在受保护的代码中发生什么。

    finally 代码块出现在最后一个 catch 块之后并且语法如下
    */
       int a[] = new int[2];
      try{
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }finally{
         // a[0] = 6;
         // System.out.println("First element value: " +a[0]);
         // System.out.println("The finally statement is executed");
         System.out.println("finally");
      }

      /*
        Notice:
            catch 在没有 try 关键字的情况下是不能够出现的。
            try/catch 语句块中并不是强制出现 finally 块。
            try 语句块不能独立存在(即没有任何 catch 和 finally 块)。
            在 try catch 和 finally 块之间是不能出现任何代码的。
      */
}
}