Given the code fragment:

public static void main(String[] args) {
    ArrayList myList = new ArrayList();
    String[] myArray;
    try {
        while (true) {
            myList.add("My String");
        }
    } catch (RuntimeException re) {
        System.out.println("Caught a RuntimeException");
    } catch (Exception e) {
        System.out.println("Caught a Exception");
    }
    System.out.println("Ready to use");
}

What is the result?

A. Execution terminates in the first catch statement, and caught a RuntimeException is printed to the console.
B. Execution terminates In the second catch statement, and caught an Exception is printed
to the console.
C. A runtime error is thrown in the thread "main".
D. Execution completes normally, and Ready to use is printed to the console.
E. The code fails to compile because a throws keyword is required.

题解

第 11 行的 while 循环会不断运行,因为没有任何的中止条件,所以会不断加入「My String」字符串至 myList 这个 ArrayList 对象中。当内存不够将字符串添加至 ArrayList 对象的时候,就会产生 OutOfMemoryError。由于 try-catch 并没有处理 Error 类别底下的 OutOfMemoryError,因此会继续将 OutOfMemoryError 往外抛出,但是并没有任何程序去处理这个 OutOfMemoryError,线程便会原封不动地将其抛出,然后中止运行。