java如何处理异常
异常处理的基本概念
Java中的异常处理机制通过try-catch-finally块实现,用于捕获和处理程序运行时可能出现的错误。异常分为Checked Exception(编译时检查,如IOException)和Unchecked Exception(运行时异常,如NullPointerException)。
使用 try-catch 块
通过try块包裹可能抛出异常的代码,catch块捕获并处理特定类型的异常:
try {
int result = 10 / 0; // 抛出 ArithmeticException
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
多重 catch 块
可以捕获多种异常,按顺序匹配第一个符合的catch块:
try {
int[] arr = new int[5];
arr[10] = 5; // 抛出 ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("算术异常");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界: " + e.getMessage());
}
finally 块
无论是否发生异常,finally块中的代码都会执行,常用于释放资源(如关闭文件流):
try {
FileInputStream file = new FileInputStream("test.txt");
} catch (IOException e) {
System.out.println("文件读取错误");
} finally {
System.out.println("资源清理完成");
}
throws 声明异常
在方法签名中使用throws声明可能抛出的异常,由调用者处理:
public void readFile() throws IOException {
FileInputStream file = new FileInputStream("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
Java 7+支持自动关闭实现了AutoCloseable的资源(如流),无需显式调用close():
try (FileInputStream file = new FileInputStream("test.txt")) {
// 自动关闭文件流
} catch (IOException e) {
System.out.println("IO异常");
}
异常处理的最佳实践
- 避免捕获过于宽泛的异常(如直接捕获
Exception),应针对具体异常类型处理。 - 在
finally块中释放资源,或使用try-with-resources简化代码。 - 自定义异常应提供有意义的错误信息,便于调试。
- 日志记录异常信息(如使用
e.printStackTrace()或日志框架)。





