在 Java 中,哪些异常是检查型异常(Checked Exceptions),哪些是运行时异常(Runtime Exceptions)?请分别举例说明,并解释为什么它们被这样分类。
在 Java 中,异常分为检查型异常(Checked Exceptions)和运行时异常(Runtime Exceptions),它们的分类主要基于异常的处理方式和使用场景。以下是详细说明:
### 检查型异常(Checked Exceptions)
检查型异常是指那些在编译时就必须被处理的异常。如果代码中可能抛出检查型异常,必须显式地捕获或声明抛出(通过 `throws` 关键字),否则代码无法通过编译。检查型异常通常表示程序可以预期的错误情况,例如文件不存在、网络连接中断等。
#### 常见的检查型异常及示例
1. `IOException`:
当进行文件读写操作时,如果文件不存在或权限不足,可能会抛出 `IOException`。
```java
try {
FileInputStream file = new FileInputStream("nonexistent.txt");
} catch (IOException e) {
System.out.println("文件读取失败: " + e.getMessage());
}
-
ClassNotFoundException: 当尝试加载一个不存在的类时,会抛出此异常。try { Class.forName("com.example.NonExistentClass"); } catch (ClassNotFoundException e) { System.out.println("类未找到: " + e.getMessage()); } -
SQLException: 在进行数据库操作时,可能会抛出SQLException,例如连接失败或 SQL 语法错误。try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/nonexistent_db", "user", "password"); } catch (SQLException e) { System.out.println("数据库连接失败: " + e.getMessage()); }
为什么是检查型异常?
检查型异常通常表示程序可以恢复或需要用户干预的情况,编译器强制开发者处理这些异常,以确保程序的健壮性。
运行时异常(Runtime Exceptions)
运行时异常是指那些在程序运行时才会被检测到的异常。它们通常是由于程序逻辑错误引起的,例如空指针引用或数组越界。运行时异常不需要显式捕获或声明抛出,但可以通过 try-catch 块捕获。
常见的运行时异常及示例
-
NullPointerException: 当调用一个空对象的方法或属性时,会抛出此异常。String str = null; try { System.out.println(str.length()); } catch (NullPointerException e) { System.out.println("空指针异常: " + e.getMessage()); } -
ArrayIndexOutOfBoundsException: 当访问数组的非法索引时,会抛出此异常。int[] arr = {1, 2, 3}; try { System.out.println(arr[3]); // 索引越界 } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组越界异常: " + e.getMessage()); } -
ArithmeticException: 当进行不合法的算术运算时,例如除以零,会抛出此异常。try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("算术异常: " + e.getMessage()); }
为什么是运行时异常?
运行时异常通常表示程序中的逻辑错误,而不是外部环境问题。它们可以通过代码设计来避免,而不是通过异常处理来恢复。因此,运行时异常不被强制要求捕获或声明。
总结
- 检查型异常:必须显式处理,表示程序可以预期的错误,如
IOException、ClassNotFoundException等。 - 运行时异常:无需显式处理,表示程序逻辑错误,如
NullPointerException、ArrayIndexOutOfBoundsException等。