はらこメモ

プログラミングに関して調べたことについてのメモ書きです。言語はバラバラ…。

「Java」例外チェーン

try-catch文でcatch文で例外が発生した場合、
そのままスローすると、元の例外を潰してしまう。

initCause()メソッドで元の例外のスタックトレース
catch文で発生した例外に追加することができる。

public class ExceptionTestMain {
	public static void main(String[] args) {
		try {
			System.out.println("exception test start");
			try{
				//例外1
				throw new Exception("exception 1");
			}catch(Exception e1){
				try{
					//さらに例外2が発生
					throw new Exception("exception 2");
				}catch(Exception e2){
					//例外2に例外1をチェインする。
					e2.initCause(e1);
					throw e2;
				}
			}
		} catch (Exception e) {
			//例外のスタックトレースを表示
			e.printStackTrace();
		}
	}
}

実行結果

exception test start
java.lang.Exception: exception 2
	at exceptionTest.ExceptionTestMain.main(ExceptionTestMain.java:16)
Caused by: java.lang.Exception: exception 1
	at exceptionTest.ExceptionTestMain.main(ExceptionTestMain.java:12)