Java 的 Throwable 类有哪些子类?请说明它们之间的区别以及各自的使用场景。
在 Java 中,Throwable 类是异常和错误的基类,其子类主要分为两大类:Error 和 Exception。而 Exception 又可以进一步分为检查异常(Checked Exception)和非检查异常(Unchecked Exception)。以下是这些子类的区别以及它们的使用场景。
1. Error
Error 表示严重的问题,通常由 JVM 或底层系统引发,应用程序通常无法处理或恢复。常见的 Error 子类包括:
-
OutOfMemoryError:表示 JVM 内存不足,无法为新对象分配空间。 示例:当尝试加载一个巨大的文件到内存中时,可能会抛出此错误。
public class OutOfMemoryErrorExample { public static void main(String[] args) { try { List<String> list = new ArrayList<>(); while (true) { list.add("This will cause OutOfMemoryError"); } } catch (OutOfMemoryError e) { System.out.println("Caught OutOfMemoryError!"); } } } -
StackOverflowError:表示方法调用栈溢出,通常是因为递归调用没有终止条件。 示例:
public class StackOverflowErrorExample { public static void recursiveMethod() { recursiveMethod(); // 无限递归 } public static void main(String[] args) { try { recursiveMethod(); } catch (StackOverflowError e) { System.out.println("Caught StackOverflowError!"); } } }
2. Exception
Exception 表示程序可以处理的异常情况。它分为检查异常和非检查异常。
检查异常(Checked Exception)
这类异常必须在代码中显式捕获或声明抛出,通常在方法签名中使用 throws 关键字。典型的检查异常有:
-
IOException:表示输入输出操作失败,如文件读写错误。 示例:
import java.io.File; import java.io.FileReader; import java.io.IOException; public class IOExceptionExample { public static void readFile(String path) throws IOException { File file = new File(path); FileReader reader = new FileReader(file); // 可能抛出 IOException reader.close(); } public static void main(String[] args) { try { readFile("nonexistent.txt"); } catch (IOException e) { System.out.println("Caught IOException: " + e.getMessage()); } } } -
SQLException:表示与数据库交互时发生错误。 示例:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class SQLExceptionExample { public static void connectToDatabase() throws SQLException { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nonexistent_db", "user", "password"); conn.close(); // 可能抛出 SQLException } public static void main(String[] args) { try { connectToDatabase(); } catch (SQLException e) { System.out.println("Caught SQLException: " + e.getMessage()); } } }
非检查异常(Unchecked Exception)
这类异常通常由于编程错误引发,不需要显式捕获或声明。非检查异常继承自 RuntimeException,常见的子类有:
-
NullPointerException:表示尝试访问
null对象的成员。 示例:public class NullPointerExceptionExample { public static void main(String[] args) { String str = null; try { System.out.println(str.length()); // 抛出 NullPointerException } catch (NullPointerException e) { System.out.println("Caught NullPointerException!"); } } } -
IllegalArgumentException:表示传递给方法的参数不合法。 示例:
public class IllegalArgumentExceptionExample { public static void setAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } System.out.println("Age is set to " + age); } public static void main(String[] args) { try { setAge(-5); // 抛出 IllegalArgumentException } catch (IllegalArgumentException e) { System.out.println("Caught IllegalArgumentException: " + e.getMessage()); } } }
总结
- Error 表示严重问题,通常无法恢复,如内存溢出或栈溢出。
- Exception 表示程序可以处理的异常,分为检查异常和非检查异常:
- 检查异常要求显式处理,适用于可预测的异常情况(如文件未找到)。
- 非检查异常通常由编程错误引发,不需要显式处理(如空指针异常)。
理解这些异常的分类和使用场景,有助于编写健壮且可维护的代码。