什么是异常?

异常(Exception)是程序在编译期或运行期发生的、干扰正常指令流的事件。Java 使用异常处理机制将异常信息封装为对象,并提供了捕获与处理的语法

异常就是错误对象

编译时异常

运行时异常

抛异常

捕获异常,默认是JVM来捕获异常,程序会中断

异常的分类

1.RuntimeException:运行时异常:一般不手动处理,出问题了再处理

2.其他Exception:必须要经过手动处理

2.Error:一般指的是系统级错误

异常体系结构

所有异常类都继承自 Throwable,其下分为两个主要分支:
Throwable
├── Error
│   └── 严重问题,如 OutOfMemoryError、StackOverflowError,程序无法处理
└── Exception
    ├── 受检异常(Checked Exception)
    │   ├── IOException(IO异常)
    │   ├── SQLException(数据库异常)
    │   ├── ClassNotFoundException
    │   └── 自定义异常(继承 Exception)
    └── 非受检异常(Unchecked Exception / RuntimeException)
        ├── ArithmeticException(除以0)
        ├── NullPointerException(空指针)
        ├── ArrayIndexOutOfBoundsException(数组越界)
        ├── ClassCastException(类型转换异常)
        ├── IllegalArgumentException(非法参数)
        └── 自定义运行时异常(继承 RuntimeException)

受检异常(Checked Exception)

编译器会检查此类异常,必须通过 throws 声明或 try-catch 处理

代表:IOException、SQLException、ClassNotFoundException

非受检异常(Unchecked Exception)

编译器不强制处理,通常由编程错误导致

代表:NullPointerException、ArithmeticException、ArrayIndexOutOfBoundsException

所有 RuntimeException 及其子类都是非受检异常

错误(Error)

由 JVM 抛出,程序无法处理(如内存溢出)

一般不捕获也不抛出。

异常处理关键字

关键字作用
try包裹可能抛出异常的代码块
catch捕获并处理特定类型的异常
finally无论是否发生异常,都会执行的代码块(用于释放资源)
throw手动抛出异常对象(方法体内)
throws声明方法可能抛出的异常类型(方法签名后)

异常的处理

try...catch

try{

        尝试执行的代码

}catch(Exception e){

        处理异常的代码

}finally{

        最终的

}

try-catch
try {
    // 可能发生异常的代码
    int result = 10 / 0;
} catch (ArithmeticException e) {
    // 处理异常
    System.out.println("除数不能为0:" + e.getMessage());
}
多重 catch
try {
    int[] arr = new int[5];
    arr[10] = 100;
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("数组越界");
} catch (Exception e) {
    System.out.println("其他异常");
}
try-catch-finally
FileInputStream fis = null;
try {
    fis = new FileInputStream("test.txt");
    // 读取文件
} catch (IOException e) {
    System.out.println("文件操作异常");
} finally {
    // 无论是否发生异常,都会执行
    if (fis != null) {
        try { fis.close(); } catch (IOException e) { }
    }
}
throws和throw
throws

表示方法准备要扔出来一个异常

产生的错误尽可能自己处理,少向外抛出异常

throw

表示向外抛出异常

throw 手动抛出异常
public void setAge(int age) {
    if (age < 0 || age > 150) {
        throw new IllegalArgumentException("年龄必须在0~150之间");
    }
    this.age = age;
}
throws 声明抛出异常
public void readFile(String path) throws IOException {
    FileInputStream fis = new FileInputStream(path);
    // ...
}
自定义异常

直接继承Exception或者RuntimeException来实现自定义异常

受检异常(继承 Exception
class MyCheckedException extends Exception {
    public MyCheckedException(String message) {
        super(message);
    }
}
非受检异常(继承 RuntimeException
class MyUncheckedException extends RuntimeException {
    public MyUncheckedException(String message) {
        super(message);
    }
}

更多推荐