java如何捕获异常
捕获异常的基本语法
在Java中,使用try-catch块捕获异常。将可能抛出异常的代码放在try块中,异常处理逻辑放在catch块中。
try {
// 可能抛出异常的代码
int result = 10 / 0; // 抛出ArithmeticException
} catch (ArithmeticException e) {
// 处理异常
System.out.println("捕获到算术异常: " + e.getMessage());
}
捕获多个异常
可以为一个try块添加多个catch块,分别处理不同类型的异常。
try {
// 可能抛出多种异常的代码
int[] arr = new int[5];
arr[10] = 50; // 抛出ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("算术异常: " + e.getMessage());
}
使用finally块
finally块中的代码无论是否发生异常都会执行,通常用于释放资源(如关闭文件或数据库连接)。
try {
// 可能抛出异常的代码
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
} finally {
System.out.println("无论是否异常,finally块都会执行");
}
捕获所有异常
使用Exception类可以捕获所有子类异常(不推荐滥用,应尽量明确异常类型)。
try {
// 可能抛出多种异常的代码
String str = null;
System.out.println(str.length()); // 抛出NullPointerException
} catch (Exception e) {
System.out.println("捕获到异常: " + e.getClass().getName());
}
自定义异常处理
可以通过继承Exception类创建自定义异常,并在catch块中处理。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
try {
throw new CustomException("自定义异常示例");
} catch (CustomException e) {
System.out.println("捕获自定义异常: " + e.getMessage());
}
注意事项
- 避免空的
catch块,至少应记录异常信息。 - 优先捕获具体异常,而非直接捕获
Exception。 - 使用
try-with-resources简化资源管理(Java 7+)。
// try-with-resources示例(自动关闭资源)
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
}






