Java 异常体系与异常处理
异常处理是 Java 程序健壮性的重要保障。理解异常体系和处理机制是编写可靠程序的基础。本章将详细介绍 Java 中的异常处理。
异常概念(检查型异常 vs 非检查型异常)
什么是异常
异常(Exception)是程序运行时发生的错误或意外情况。
// 常见的异常情况
int[] arr = new int[5];
int value = arr[10]; // ArrayIndexOutOfBoundsException
String str = null;
int length = str.length(); // NullPointerException
int result = 10 / 0; // ArithmeticException
异常的分类
Java 异常分为两大类:
- 检查型异常(Checked Exception):必须处理的异常
- 非检查型异常(Unchecked Exception):可以不处理的异常
异常类层次结构
Throwable
├── Error(错误,非检查型)
│ ├── OutOfMemoryError
│ ├── StackOverflowError
│ └── ...
└── Exception(异常)
├── RuntimeException(运行时异常,非检查型)
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ ├── IllegalArgumentException
│ └── ...
└── 其他 Exception(检查型异常)
├── IOException
├── SQLException
└── ...
检查型异常
检查型异常(Checked Exception)是编译时必须处理的异常,如果不处理,代码无法编译通过。
// 检查型异常示例
import java.io.FileReader;
import java.io.IOException;
public void readFile() {
// ❌ 编译错误:必须处理 IOException
// FileReader reader = new FileReader("file.txt");
// ✅ 正确:使用 try-catch 处理
try {
FileReader reader = new FileReader("file.txt");
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
// ✅ 正确:使用 throws 声明
// public void readFile() throws IOException { }
}
常见的检查型异常:
IOException:输入输出异常SQLException:数据库异常ClassNotFoundException:类未找到异常
非检查型异常
非检查型异常(Unchecked Exception)是运行时异常,编译时不强制处理。
// 非检查型异常示例
public void method() {
// 可以不处理,但运行时可能抛出异常
int[] arr = new int[5];
int value = arr[10]; // ArrayIndexOutOfBoundsException
String str = null;
int length = str.length(); // NullPointerException
}
常见的非检查型异常:
NullPointerException:空指针异常ArrayIndexOutOfBoundsException:数组越界异常IllegalArgumentException:非法参数异常ArithmeticException:算术异常
try-catch-finally 语句结构
基本语法
try {
// 可能抛出异常的代码
} catch (ExceptionType e) {
// 处理异常
} finally {
// 无论是否发生异常都会执行
}