Throwable - getCause()
1 定义
the cause of this throwable or null if the cause is nonexistent or unknown.
返回引起此异常的原因或者
null
(不存在原因或者未知情况)。
2 举例
public class Throwable$getCauseTest {
public static void main(String[] args) {
getCause1();
getCause2();
}
public static void getCause1() {
try {
throw new RuntimeException("main error!");
} catch (Exception e) {
System.out.println(e.getCause() instanceof RuntimeException);
System.out.println("e:" + e + "; e.getCause():" + e.getCause());
}
}
public static void getCause2() {
Runnable r1 = () -> {
throw new RuntimeException("Thread error!");
};
Future<Integer> task = Executors.newSingleThreadExecutor().submit(r1, 1);
try {
task.get();
} catch (Exception e) {
System.out.println(e.getCause() instanceof RuntimeException);
System.out.println("e:" + e + "; e.getCause():" + e.getCause());
}
}
}
// 输出结果
false
e:java.lang.RuntimeException: main error!; e.getCause():null
true
e:java.util.concurrent.ExecutionException: java.lang.RuntimeException: Thread error!;
e.getCause():java.lang.RuntimeException: Thread error!
3 总结
例如线程池抛出的异常,最外层是
ExecutionException
,所以getCause()
能够获取到里层RuntimeException
;直接捕获抛出的异常,调用
getCause()
则返回的null
;
感谢阅读,下次再见。ヾ( ̄▽ ̄)ByeBye!