qaq
异常
- 最上层父类:
Exception - 分为:编译时异常、运行时异常
- 编译时异常:直接继承于
Exception,编译阶段就会错误提示(java文件 -> 字节码文件) - 运行时异常:
RuntimeException本身和子类,运行时出错误提示(字节码文件 -> 运行结果) 
 - 编译时异常:直接继承于
 
异常的处理方式
JVM默认处理方式
- 把异常名字、异常原因、异常出现位置以红色字体输出在控制台
 - 程序中止
 
自己处理
- 可以让程序继续执行
 
int[] arr = {1, 2, 3};
try {
    System.out.println(arr[5]);
} catch(ArrayIndexOutOfBoundsException e) {
    System.out.println("索引越界");
}
System.out.println("Hello");//执行成功try中代码出现异常就中止,进入对应的catch
int[] arr = {1, 2, 3, 4};
try {
    System.out.println(arr[10]);//ArrayIndexOutOfBoundsException
    System.out.println(2/0);//ArithmeticException
} catch(ArrayIndexOutOfBoundsException e) {
    System.out.println("索引越界");
}
System.out.println("Hello");
//输出:
//索引越界
//Hello若
try中可能遇到多个异常,写多个catch与之对应。- 注意:如果这些异常中存在父子关系,父类写下面
 - 多个
catch也不能同时捕获多个异常,碰到第一个异常就退出了 
JDK7之后,可以在catch中捕获多个种类的异常
- 表示出现了A异常或B异常,采用同一种方案
 
try { } catch(ArrayIndexOutOfBoundsException | ArithmeticException e) { }try中遇到的异常没被捕获,采用JVM默认方法处理
异常的常见方法
Throwable的成员方法
public void printStackTrace():把异常信息输出在控制台,不会停止程序运行public String toString():返回这个可抛出的简短描述public String getMessage():返回此throwable的详细消息字符串
抛出异常
throws:标记在方法定义处- 编译时异常:必须写
 - 运行时异常:可以不写
 
public void method() throws 异常1, 异常2... {
    ...
}throw:手动抛出异常对象,抛出后中止
public static int getMax(int[] arr) {
    if(arr == null) {
        throw new NullPointerException();
    }
    if(arr.length == 0) {
        throw new ArrayIndexOutOfBoundsException();
    }
    ...
}自定义异常
主要是写自定义的名字
- 定义异常类
 - 继承
 - 写空参和带参构造
 
public class NameFormatException extends RuntimeException {
    public NameFormatException() {
    }
    public NameFormatException(String message) {
        super(message);
    }
}try catch finally
JDK7:IO流中捕获异常的写法
只有实现了AutoCloseable接口的类才能在小括号中创建对象
public static void main(String[] args) {
    try(FileInputStream fis = new FileInputStream("");
       FileOutputStream fos = new FileOutputStream("")) {
    } catch(IOException e) {
        e.printStackTrace();
    }
}资源自动释放
JDK9
public static void main(String[] args) throws FileNotFoundException {//因为对象创建在外面,所以需要抛出异常
    FileInputStream fis = new FileInputStream("");
    FileOutputStream fos = new FileOutputStream("");
    try(fis;fos) {
        
    } catch(IOException e) {
        e.printStackTrace();
    }
}