到第九级,我们已经对列表集合和异常有了一些了解。综合起来就是:在执行以下代码时捕获异常:ArrayList<String> list = new ArrayList<String>(); String s = list.get(18); 捕获并在屏幕上显示异常,指示其类型。 捕获执行以下代码时发生的异常(并显示其类型): ArrayList<String> list = new ArrayList<String>(); String s = list.get(18); 要求: 程序应在屏幕上显示一条消息。 程序必须有一个 try-catch 块。 程序必须捕获特定类型的异常,而不是所有可能的异常(即不是 Exception)。 显示的消息必须包含发生的异常类型。 不要删除 main 方法中的现有代码。
时间: 2024-02-18 18:04:36 浏览: 77
好的,以下是针对该任务的代码:
```java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
try {
String s = list.get(18); // 产生索引越界异常
} catch (IndexOutOfBoundsException e) {
System.out.println("捕获到异常:" + e);
}
}
}
```
该程序使用了 try-catch 块来捕获 `IndexOutOfBoundsException` 类型的异常,这是因为 `list.get(18)` 会抛出该异常。在 catch 块中,程序打印了捕获到的异常对象 `e`,以及它的类型。
程序的执行结果应该是:
```
捕获到异常:java.lang.IndexOutOfBoundsException: Index 18 out of bounds for length 0
```
阅读全文
相关推荐
















