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-cache並沒有處理Error類別底下的OutOfMemoryError,因此會繼續將OutOfMemoryError往外拋出,但是並沒有任何程式去處理這個OutOfMemoryError,執行緒變會原封不動地將其拋出,然後中止執行。