java通过异常堆栈查找发生异常的直接原因(使用e.getCause()) |
您所在的位置:网站首页 › cause所有意思 › java通过异常堆栈查找发生异常的直接原因(使用e.getCause()) |
当异常发生以后,并没有第一时间进行捕获处理,而是继续向上一级调用抛出异常,在经过几次向上抛出异常之后,所获取的异常已经无法直接反应错误原因了。 try{ Method m = ...; m.invoke(...);//反射调用方法 }catch(Exception e){ System.out.println(e.getMessage); //获取不到抛出的异常信息 }当抛出异常的地方已经定义成指定类型的异常类,比如下面的异常类。 public class BusinessException extends RuntimeException { private static final long serialVersionUID = 1L; protected final String message; public BusinessException(String message) { this.message = message; } public BusinessException(String message, Throwable e) { super(message, e); this.message = message; } @Override public String getMessage() { return message; } }如果我们希望捕获我们自定义的异常类信息,进行处理,则可以按照下面的方式进行处理: try{ Method m = ...; m.invoke(...);//反射调用方法 }catch(Exception e){ Throwable cause = e.getCause(); while (cause != null) { // 如果是我们定义的异常 if (cause instanceof BusinessException) { String message = cause.getMessage(); break; } cause = cause.getCause(); } }这里只是以反射调用举例,也适用于使用了spi机制以后,spi模块抛出的异常,在业务模块中进行捕获处理,这种方式也适合其它调用层次多的场景。 cause的字面意思也是原因的意思,也就是获取发生异常的原因。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |