开始使用免费开始使用

RuntimeException

RuntimeExceptions 在代码中不要求必须使用 try/catch 块。通常通过良好的编码实践可以避免它们。不过,当错误未被发现且 RuntimeException 未被捕获时,会导致应用程序失败,并显示用户未必能理解的问题信息。在本练习中,您将看到在不捕获可能的 RuntimeException 时会发生什么,以及在使用 try/catch 捕获时会发生什么。

本练习是课程的一部分

Java 的数据类型与异常

查看课程

练习说明

  • 查看此应用中的 withoutTryCatch()withTryCatch 方法,并注意它们的差异。
  • 在不做任何修改的情况下运行应用程序——这会执行 withoutTryCatch() 方法并触发一个 RuntimeException
  • 注释掉第 5 行,并取消注释第 7 行,然后重新运行应用程序。这次会执行 withTryCatch() 方法,从而处理该 RuntimeException

交互式实操练习

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

public class RuntimeExceptionHandling {

	public static void main(String[] args) {
		// Comment out this line
		withoutTryCatch();
		// Uncomment this line
		// withTryCatch();
	}

	public static void withoutTryCatch() {
		String[] mounts = { "Everest", "K2", "Kangchenjunga", "Lhotse" };
		String selectedMount = mounts[4];
		System.out.println("Selected item is: " + selectedMount);
	}

	public static void withTryCatch() {
		try {
			String[] mounts = { "Everest", "K2", "Kangchenjunga", "Lhotse" };
			String selectedMount = mounts[4];
			System.out.println("Selected item is: " + selectedMount);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Oops - made a mistake accessing the mounts array with a bad index.");
		}
	}
}
编辑并运行代码