Checked Exception in Java

2025年4月8日 | 阅读 5 分钟

受检异常 (Checked exceptions) 是在编译时进行检查的异常。它也被称为编译时异常。Java 编译器强制开发者处理它们。

如果一个可能抛出受检异常的方法没有使用 try-catch 块来处理它,或者没有使用 throw 关键字来声明它,那么程序将无法编译。它们通常由外部因素引起,例如文件处理、数据库访问或网络通信失败。

受检异常的类型

受检异常的类型有:

  1. IOException
  2. SQLException
  3. ClassNotFoundException
  4. InterruptedException
  5. FileNotFoundException
  6. ParseException
  7. MalformedURLException

受检异常的优点

  1. 编译时检查:Java 编译器确保在程序运行前处理受检异常。
  2. Exception 的子类:受检异常是 Exception 的直接子类,但不包括 RuntimeException。
  3. 强制正确处理:由于编译器强制处理,程序会变得更加稳定和可预测。

受检异常的常见示例

1. IOException

当输入或输出操作失败时,例如尝试读取一个不存在的文件时,会发生 IOException。

示例

当我们编译上面的程序时,会得到以下异常。

Main.java:15: error: unreported exception IOException; must be caught or declared to be thrown
    String input1 = br.readLine();  
                               ^
Main.java:19: error: unreported exception IOException; must be caught or declared to be thrown
    String input2 = br.readLine();  

2. SQLException

当出现与数据库连接相关的问题时,例如无效的凭据或数据库不可用,会发生 SQLException。

示例

当我们编译上面的程序时,会得到以下异常。

Main.java:8: error: unreported exception SQLException; must be caught or declared to be thrown
    Connection con = DriverManager.getConnection("jdbc:mysql://:3306/db", "user", "password");

3. ClassNotFoundException

当 Java 尝试使用 Class.forName() 动态加载一个类,但该类在类路径中找不到时,会发生 ClassNotFoundException。

示例

当我们编译上面的程序时,会得到以下异常。

Main.java:5: error: unreported exception ClassNotFoundException; must be caught or declared to be thrown
	Class.forName("com.example.MyClass"); // The class does not exist, and a ClassNotFoundException will be thrown

4. InterruptedException

当一个线程在睡眠或等待时被中断时,会发生 InterruptedException。

示例

当我们编译上面的程序时,会得到以下异常。

Main.java:4: error: unreported exception InterruptedException; must be caught or declared to be thrown
	Thread.sleep(5000);    
	            ^
1 error

5. FileNotFoundException

当尝试打开由指定路径名表示的文件失败时,会发生 FileNotFoundException。

示例

当我们编译上面的程序时,会得到以下异常。

Main.java:11: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
            Scanner scanner = new Scanner(file);
                              ^
1 error

6. ParseException

在将字符串解析为选定格式(包括日期或更多内容)时会抛出 ParseException。它是 java.text 包的一部分。请看下面的例子。

示例

当我们编译上面的程序时,会得到以下异常。

Main.java:9: error: unreported exception ParseException; must be caught or declared to be thrown
            Date parsedDate = dateFormat.parse(invalidDate);  
                                              ^
1 error

7. MalformedURLException

当遇到无效或格式错误的 URL 时,会抛出 MalformedURLException。它是 java.net 包的一部分。请看下面的程序。

示例

当我们编译上面的程序时,会得到以下异常。

Main.java:6: error: unreported exception MalformedURLException; must be caught or declared to be thrown
		URL url = new URL(invalidURL);  

处理受检异常

在 Java 中处理受检异常主要有两种方法:

  1. 使用 try-catch 块
  2. 使用 throws 关键字

1. 使用 try-catch 块

我们可以使用 try-catch 块来处理受检异常。

要阅读更多关于 try-catch 块 的内容

示例

输出

如果文件 nonexistent.txt 不存在

Error: The specified file was not found!

如果文件 nonexistent.txt 存在,它的内容将被打印出来

2. 使用 throws 关键字

throws 关键字将异常传播给调用方法进行处理或进一步传播。

要阅读更多关于 Java throws 关键字 的内容

示例

编译并运行

输出

Enter your name
Amit
Welcome Amit

何时在 Java 中使用受检异常?

应在可预测的事件中使用受检异常,以防止不可避免的事件。如果异常是受检异常,代码可以从中恢复。如果错误看起来可以通过受检异常来解决,那么就使用受检异常。它主要用于测试代码的边缘情况。

通常,在测试阶段,受检异常会派上用场。


下一主题