java 中处理多重异常的正确做法是将子类异常放在父类异常之前,并使用多个 catch 块分别捕获。这样能确保更具体的异常类型被优先匹配,避免被宽泛的父类异常吞没。若顺序颠倒,编译器会报错提示不可达代码。

NumberFormatException 和 ArithmeticException 如何区分处理
当解析字符串或执行算术运算时,可以分别捕获 NumberFormatException 和 ArithmeticException。这两个异常没有继承关系,因此顺序不影响结果,但建议按发生频率或重要性排列。具体做法是在同一个 try 块后紧跟两个 catch 块,分别处理输入错误和计算错误。

import java.util.Scanner;
public class MultiCatchDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number: ");
String input = scanner.next();
System.out.print("Enter divisor: ");
String divInput = scanner.next();
try {
int num = Integer.parseInt(input);
int div = Integer.parseInt(divInput);
int result = num / div;
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid number format.");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
}
预期输出:输入非数字字符时打印“Invalid number format.”;输入除数为0时打印“Cannot divide by zero.”。
IOException 与 FileNotFoundException 的捕获顺序
FileNotFoundException 是 IOException 的子类。在捕获文件操作异常时,必须先写 FileNotFoundException 的 catch 块,再写 IOException 的 catch 块。如果反过来,IOException 会先匹配所有 IO 异常,导致 FileNotFoundException 的块成为不可达代码,编译器将拒绝编译。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

import java.io.*;
public class FileCatchOrder {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("nonexistent.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO error: " + e.getMessage());
}
}
}
预期输出:因文件不存在,打印“File not found: nonexistent.txt”。
try-with-resources 中如何处理关闭时的异常
在使用 try-with-resources 时,如果资源关闭抛出异常,而 try 块中也抛出了异常,JVM 会将关闭异常作为 suppressed exception 附加到主异常上。可以通过 getSuppressed() 方法获取这些异常。这种做法确保了即使关闭失败,原始异常也能被正确传播和处理。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










