Throwable の getCause() で null にならないまで参照していく方法になり、
ネット検索すると腐るほどサンプルコードが出てくるだろう。。
while ループを良く見かけるが、個人的には、for文ループの方が良いと思っている。
}catch(Exception e){ for(Throwable ext=e; ext != null; ext=ext.getCause()){ // TODO Throwable ext に対する処理 }
Stream filter を使って、根本原因の例外を捕捉する場合
}catch(Exception e){ Optional<Throwable> rootCause = Stream.iterate(e, Throwable::getCause) .filter(ext->ext.getCause()==null) .findFirst(); // TODO rootCause.get() で参照
Java9 からの Stream takeWhile を使って、
例外を cause(原因)を掘り下げたリスト
}catch(Exception e){ List<Throwable> list = Stream.iterate(e, Throwable::getCause) .takeWhile(ext->ext!= null) .collect(Collectors.toList());
例外を cause(原因)を掘り下げたリストを逆順に参照
→ 発生する Exceptionの順にリストにする。
}catch(Exception e){ List<Throwable> list = Stream.iterate(e, Throwable::getCause) .takeWhile(ext->ext != null) .collect(Collectors.toList()) .stream() .collect(ArrayList::new, (r, t)->r.add(0, t), (r, u)->r.addAll(0, u));