Throwables模块
该模块是一个比较好的处理异常的类,可以完成以下几件事情:
- 获取异常链
- 获取异常发生的最底层原因
- 异常的过滤
- 把受检查的异常转换为运行时异常
常用的一些方法
- 获取整个的异常链
List<Throwable> list = null;
try {
try {
try {
int i = 10 / 0;
} catch (Exception e) {
throw new SQLException("Middle tier exception", e);
}
} catch (Exception e) {
throw new IllegalStateException("Last exception", e);
}
} catch (Exception e) {
list = Throwables.getCausalChain(e);
}
- 获取最底层链
Throwables.getRootCause(e).getMessage()
- 过滤关心的异常
try {
throw new IOException();
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, NullPointerException.class);
System.out.println("Hello World!");
}