开始使用免费开始使用

受检异常

RuntimeException 相反,所有受检异常都必须使用 try-catch 块处理,否则代码无法编译,更谈不上运行。本练习将向您展示,必须在受检异常外包一层 try/catch,否则应用将无法编译、也无法运行。

本练习是课程的一部分

Java 的数据类型与异常

查看课程

练习说明

  • 先不做任何修改直接运行示例代码,您会看到对 Class.forName() 的调用需要处理。如果未处理,会导致编译错误(error: compilation failed)。
  • 取消注释 try、catch,以及在 catch 块中显示的消息。
  • 现在再次运行应用,您会看到由于已处理受检异常,应用可以编译并运行。

交互式实操练习

通过完成这段示例代码来试试这个练习。

public class CheckedExceptionHandling {

	public static void main(String[] args) {
    	// Uncomment the try block
		// try {
			Class.forName("java.util.ArrayList");
		// Uncomment the catch block for ClassNotFoundException
		// } catch (ClassNotFoundException e) {
        	// Uncomment the message for the exception
			// System.out.println("Work goes here to recover from the checked exception");
        // Uncomment the end of the try/catch
		// }
		System.out.println("Work complete");
	}
}
编辑并运行代码