java语言如何进行异常处理
Java异常处理的基本结构
Java通过try-catch-finally块实现异常处理。将可能抛出异常的代码放入try块,捕获并处理异常的代码放入catch块,无论是否发生异常都会执行的代码放入finally块。
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 捕获并处理异常
System.out.println("除零错误: " + e.getMessage());
} finally {
// 清理资源或收尾操作
System.out.println("执行finally块");
}
捕获多个异常
通过多个catch块可以捕获不同类型的异常,需注意子类异常需放在父类异常之前。

try {
int[] arr = new int[5];
arr[10] = 50; // 可能抛出ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界: " + e.getMessage());
} catch (Exception e) {
System.out.println("通用异常处理: " + e.getMessage());
}
抛出异常
使用throw关键字手动抛出异常,通常用于自定义逻辑校验。
void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("年龄不合法");
}
}
声明异常
通过throws在方法签名中声明可能抛出的异常,强制调用者处理。

void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
// 文件操作代码
}
自定义异常
继承Exception或RuntimeException创建自定义异常类。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用示例
try {
throw new CustomException("自定义异常");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
try-with-resources
自动管理资源(如文件流、数据库连接),资源需实现AutoCloseable接口。
try (FileReader fr = new FileReader("file.txt")) {
// 自动关闭资源
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
}
异常处理最佳实践
- 优先捕获具体异常,而非通用
Exception。 - 避免空的
catch块,至少记录异常信息。 - 使用
finally释放非自动管理资源。 - 自定义异常应提供有意义的错误信息。





