例外から例外

(2009/4/26シンタックスハイライト追加)
Javaで例外の原因を例外それ自身にすると実行時例外が発生することを知った。
Throwable.initCauseでできる。
例外の種類は…Throwableのソースを見ればすぐわかる。

package hoge;

public class ThrowableExp {
	public static void main(String[] args) {
		Throwable t = new Throwable();
		t.initCause(t);
	}
}


これを回避するために、例外オブジェクトを2つにすると
原因に自身が含まれていても実行時例外は起こらない。
ただしThrowable.printStackTraceで再帰が止まらなくなる。

package hoge;

public class ThrowableExp2 {
	public static void main(String[] args) {
		Throwable t1 = new Throwable();
		Throwable t2 = new Throwable();
		
		t1.initCause(t2);
		t2.initCause(t1);
		
		try {
			throw t1;
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}

catchしたときの変数名がeなのはEclipseに頼んだから。