java如何捕获异常
捕获异常的基本语法
在Java中,使用try-catch块捕获异常。将可能抛出异常的代码放在try块中,异常处理逻辑放在catch块中。
try {
// 可能抛出异常的代码
} catch (ExceptionType e) {
// 异常处理逻辑
}
捕获特定异常类型
可以指定具体的异常类型来捕获特定异常,例如IOException或NullPointerException。
try {
FileInputStream file = new FileInputStream("nonexistent.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
}
捕获多个异常
一个try块可以跟随多个catch块,用于处理不同类型的异常。
try {
int[] arr = new int[5];
arr[10] = 50; // ArrayIndexOutOfBoundsException
FileInputStream file = new FileInputStream("nonexistent.txt"); // FileNotFoundException
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界: " + e.getMessage());
}
使用多重捕获
Java 7及以上版本支持多重捕获,可以在一个catch块中捕获多种异常类型。

try {
// 可能抛出多种异常的代码
} catch (IOException | SQLException e) {
System.out.println("发生IO或SQL异常: " + e.getMessage());
}
使用finally块
finally块中的代码无论是否发生异常都会执行,常用于释放资源。
FileInputStream file = null;
try {
file = new FileInputStream("file.txt");
// 处理文件
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println("关闭文件时出错: " + e.getMessage());
}
}
}
使用try-with-resources
Java 7引入的try-with-resources语法可以自动关闭实现了AutoCloseable接口的资源。

try (FileInputStream file = new FileInputStream("file.txt")) {
// 处理文件
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
}
捕获并重新抛出异常
在捕获异常后,可以选择重新抛出异常或抛出一个新的异常。
try {
// 可能抛出异常的代码
} catch (IOException e) {
System.out.println("捕获到IO异常");
throw new RuntimeException("转换异常", e);
}
自定义异常捕获
可以定义自己的异常类并通过try-catch块捕获。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
try {
throw new CustomException("自定义异常");
} catch (CustomException e) {
System.out.println("捕获到自定义异常: " + e.getMessage());
}
打印异常堆栈跟踪
通过printStackTrace()方法可以打印异常的堆栈跟踪信息。
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
e.printStackTrace();
}






