java 多层异常_Java中多层异常包裹时候获取最底层的最真实异常-分析Java异常栈...

示例代码:

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

class AudienceLimitExcption extends Exception {

public AudienceLimitExcption(String message, Throwable cause) {

super(message, cause);

}

}

class Task implements Callable {

@Override

public Object call() throws Exception {

try {

System.out.println(1 / 0);

} catch (Exception e) {

throw new AudienceLimitExcption("limit error", e);

}

return 1;

}

}

代码异常1:

public class Main {

public static void main(String[] args) {

Object r = null;

ExecutorService es = Executors.newFixedThreadPool(4);

try {

Future f = es.submit(new Task());

r = f.get();

System.out.println();

} catch (Throwable e) {

System.out.println(e.getClass());

}

}

}

输出结果:class java.util.concurrent.ExecutionException  不是最真实的底层抛出去的异常。

分析异常栈:

86130666eb7f98ab19c3dd9b352fa2a8.png

会发现当cause==当前异常时候就是最真实异常,于是代码如下:

public class Main {

public static void main(String[] args) {

Object r = null;

ExecutorService es = Executors.newFixedThreadPool(4);

try {

Future f = es.submit(new Task());

r = f.get();

System.out.println();

} catch (Throwable e) {

while (e != null) {

Throwable cause = e.getCause();

if (e.equals(cause)) {

System.out.println(e);

}

e = cause;

}

}

}

}

运行发现没有输出,debug发现当e为真实异常时候,e.getCause方法返回值为null。因此if分支无法为true,所以没有输出。与上图异常栈分析结论相悖,只能查看一下getCause方法实现:

public synchronized Throwable getCause() {

return (cause==this ? null : cause);

}

JDK实现时候,当cause等于当前异常e时候直接返回null,因此正确方案如下:

public class Main {

public static void main(String[] args) {

Object r = null;

ExecutorService es = Executors.newFixedThreadPool(4);

try {

Future f = es.submit(new Task());

r = f.get();

System.out.println();

} catch (Throwable e) {

while (e != null) {

Throwable cause = e.getCause();

if (cause == null) {

System.out.println(e.getClass());

}

e = cause;

}

}

}

}

输出结果也就是1/0最真实的异常类型:class java.lang.ArithmeticException

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值