Java Gold合格への道 ~例外の再スロー~
スポンサーリンク
こんにちは。たろすです。
今回は例外の再スローについて説明します。
例外の再スロー
例外をキャッチした後に再度例外をスローすることができます。
その際に引数に元の例外を指定することで、元の例外を受け渡すことができます。
public static void main(String[] args) { try { x(); } catch (Exception e) { e.printStackTrace(); } } public static void x() throws Exception { try { y(); } catch (Exception e) { throw new Exception("x", e); // 例外の受け渡し } } public static void y() throws Exception { try { z(); } catch (Exception e) { throw new Exception("y", e); // 例外の受け渡し } } public static void z() throws Exception { throw new Exception("z"); }
元の例外の取り出し
受け渡されてきた例外はgetCauseメソッドによって取り出すことができます。
public static void main(String[] args) { try { x(); } catch (Throwable e) { while (e != null) { System.out.println(e.getMessage()); e = e.getCause(); // 例外の取り出し } } } public static void x() throws Exception { try { y(); } catch (Exception e) { throw new Exception("x", e); } } public static void y() throws Exception { try { z(); } catch (Exception e) { throw new Exception("y", e); } } public static void z() throws Exception { throw new Exception("z"); }
x y z