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,執行緒便會原封不動地將其拋出,然後中止執行。
