Java SE 25 Silver (1Z0-827-JPN) 試験 / 例外処理 ・ 無料問題 4/5
例外処理 問題4[カスタム例外の作成]
次のコードを実行したときの出力を選んでください。
class AppException extends Exception { AppException(String message, Throwable cause) { super(message, cause); }}public class Main { static int parse(String s) throws AppException { try { return Integer.parseInt(s); } catch (NumberFormatException e) { throw new AppException("bad input", e); } } public static void main(String[] args) { try { System.out.print(parse("12") + " "); System.out.print(parse("x") + " "); } catch (AppException e) { System.out.println(e.getMessage() + " " + e.getCause().getClass().getSimpleName()); } }}選択肢
- A.12 bad input NumberFormatException正解
- B.12 bad input AppException
- C.bad input NumberFormatException
- D.12 For input string: "x" NumberFormatException
解説実行して確認済み
カスタム例外は、Exception などを継承して作ります。Exception のコンストラクタにはメッセージと原因 (cause) を受け取るものがあり、super(message, cause) で渡すと、getMessage と getCause で取り出せます。"12" は変換できて 12 と出力され、"x" で発生した NumberFormatException は AppException に包んで投げ直されます。捕捉した e のメッセージは bad input、原因は NumberFormatException です。
この問題の答えは、試験の対象バージョンでコードを実際に実行して確かめています。確かめ方は運営者情報に書いています。
Java SE 25 Silver (1Z0-827-JPN) 試験 の他の分野の無料問題
ここで公開しているのは無料範囲の問題です。無料登録すると、解答の記録・ダッシュボードでの復習ができ、 プレミアムならこの問題セットの全問題と本番形式の模擬試験も解けます。