---
# System prepended metadata

title: 例外和錯誤
tags: [ocpjp]

---

# 例外和錯誤
```java=
ArrayList<String> myList = new ArrayList<String>();
		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. The code fails to compile because a throws keyword is required.
B. Execution terminates in the second catch statement, and Caught an Exception is printed to the
console.
C. Execution terminates in the first catch statements, and Caught a RuntimeException is printed to
the console.
D. Execution completes normally, and Ready to use is printed to the console.
**E. A runtime error is thrown in the thread "main"**
- [x] **Answer: E**

:::warning
while迴圈會不斷執行，因為沒有任何的中止條件，所以會不斷加入「My String」字串至myList這個ArrayList物件中。當記憶體不夠將字串添加至ArrayList物件的時候，就會產生OutOfMemoryError。由於try-cache並沒有處理Error類別底下的OutOfMemoryError，因此會繼續將OutOfMemoryError往外拋出，但是並沒有任何程式去處理這個OutOfMemoryError，執行緒變會原封不動地將其拋出，然後中止執行。
:::

---
Example:
```java=
public static void doStuff() throws ArithmeticException, NumberFormatException,Exception {
		if(Math.random() >-1) 
			throw new Exception ("Try again");
	}
	public static void main(String[] args) {
		try {
			doStuff();
		} catch (ArithmeticException | NumberFormatException | Exception e){
			System.out.println (e.getMessage()); 
		}catch (Exception e) {
			System.out.println (e.getMessage()); 
		}
	}
```
## Which modification enables the code to print Try again?
A. Comment the lines 28, 29 and 30.
B. Replace line 26 with:
} catch (Exception | ArithmeticException | NumberFormatException e) {
**C. Replace line 26 with:
} catch (ArithmeticException | NumberFormatException e) {**
D. Replace line 27 with:
throw e;
- [x] **Answer: C**
:::info
ArithmeticException和NumberFormatException均為Exception的子類別，重複包含了。
要修正這個問題，可以把第26行的Exception拿掉，因此答案是選項C。
:::

###### tags: `ocpjp`