Java 异常处理(try-catch、throws)

288 阅读1分钟

一、try...catch...

  • Java 自定义异常(Exception)

  • 格式

    try {
      可能出现异常的代码
    } catch (异常类名 变量名) {
      异常处理代码
    }
    
  • 执行流程

    1、程序从 try 里面的代码开始执行,出现异常,会自动生成一个异常类对象,该异常对象将被提交给 Java 运行时系统

    2、当 Java运行时系统 接收到异常对象时,会到 catch 中去找匹配的异常类,找到后进行异常的处理,执行完毕之后,程序还可以继续往下执行。

  • 案例代码

    public class test {
      public static void main(String[] args) {
        System.out.println("开始");
        method(); // 执行会报错的方法
        System.out.println("结束");
      }
    
      // 会报错的方法
      public static void method() {
    
        // 由于取不到数组指定下标值,则会报错抛出异常
        try {
          int[] nums = {1, 2, 3};
          System.out.println(nums[4]);
        } catch (Exception e) {
          System.out.println("数组索引不存在!");
        }
      }
    }
    

二、throws

  • 格式

    throws 异常类名;
    
  • 加在方法后面,表示该方法可能会抛出指定类型的异常错误,在外部使用还是得通过 try...catch... 来处理,throws 只是声明可能会抛出异常错误

  • 案例代码

    public class test {
      public static void main(String[] args) {
        System.out.println("开始");
        try {
          method(); // 执行会报错的方法
        } catch (Exception e) {
          System.out.println("数组索引不存在!");
        }
        System.out.println("结束");
      }
    
      // 会报错的方法
      public static void method() throws ArrayIndexOutOfBoundsException {
        // 由于取不到数组指定下标值,则会报错抛出异常
        int[] nums = {1, 2, 3};
        System.out.println(nums[4]);
      }
    }