【Java SE17 Silver 模擬試験】B-32

Java SE17 Silver 模擬試験
Java SE17 Silver 模擬試験

問題

次のコードをコンパイル、実行するとどうなりますか。

public class Main {
	public static void main(String... args) {
		try {
			new Main().test();
		} catch (Exception e) {
			System.out.println(e.getCause());
		}
	}

	public void test() throws Exception {
		try {
			throw new OutOfStockException("throw OutOfStockException");
		} catch (StockException e) {
			throw new StockException(e.getMessage(), e);
		}
	}
}

class StockException extends Exception {
	public StockException(String msg) {
		super(msg);
	}

	public StockException(String message, Throwable cause) {
		super(message, cause);
	}
}

class OutOfStockException extends StockException {
	public OutOfStockException(String msg) {
		super(msg);
	}

	public OutOfStockException(String message, Throwable cause) {
		super(message, cause);
	}
}

選択肢

A)コンパイルエラーになる

B)Exception: throw OutOfStockException が出力される

C)OutOfStockException: throw OutOfStockException が出力される

D)Throwable: throw OutOfStockException が出力される

E)ClassCastException がスローされる

F)StockException: throw OutOfStockException が出力される

解答

A)コンパイルエラーになる

B)Exception: throw OutOfStockException が出力される

C)OutOfStockException: throw OutOfStockException が出力される

D)Throwable: throw OutOfStockException が出力される

E)ClassCastException がスローされる

F)StockException: throw OutOfStockException が出力される

解説

A)コンパイルエラーになる
→ コンパイルエラーにはならない。

B)Exception: throw OutOfStockException が出力される
→ 原因は OutOfStockException であり、出力にはクラス名が含まれない。

C)OutOfStockException: throw OutOfStockException が出力される
→ 原因のクラス名とメッセージが正しく出力される。

D)Throwable: throw OutOfStockException が出力される
Throwable の出力ではなく、OutOfStockException の出力。

E)ClassCastException がスローされる
→ このコードには ClassCastException は発生しない。

F)StockException: throw OutOfStockException が出力される
→ 原因の StockException ではなく、実際は OutOfStockException が原因です。

前の問題へ SE17_B-31

次の問題へ SE17_B-33

対象資格:Java SE17 認定資格