java异常链处理

jdk1.4后的,所有异常根类Throwable部分代码


/** 描述异常的信息 */
private String detailMessage;

/** 本异常包裹的原因异常,默认状态下,cause指向本异常 */
private Throwable cause = this;

/** 在构造函数初始化异常的细节信息 */
public Throwable(String message, Throwable cause) {
fillInStackTrace();
detailMessage = message;
this.cause = cause;
}

public Throwable(Throwable cause) {
// 将当前线程的堆栈内容记录在本异常的追踪信息中
fillInStackTrace();
// 记录本异常的细节信息,如果cause为null,则detailMessage为null,否则为cause.toString()
detailMessage = (cause==null ? null : cause.toString());
// 记录异常原因
this.cause = cause;
}

public Throwable(Throwable cause, String message) {
// 将当前线程的堆栈内容记录在本异常的追踪信息中
fillInStackTrace();
// 记录本异常的细节信息
detailMessage = message;
// 记录异常原因
this.cause = cause;
}

/** 获得原因异常,如果cause指向本异常,说明原因异常不存在或未知,返回null */
public Throwable getCause() {
return (cause==this ? null : cause);
}

/** 初始化原因异常,此方法最多调用一次 */
public synchronized Throwable initCause(Throwable cause) {
// 如果原因异常不指向本异常,即原因异常已经存在,抛出异常:说明不能覆盖
if (this.cause != this)
throw new IllegalStateException("Can't overwrite cause");
// 如果输入参数cause指向本异常,抛出异常:不可以把自身作为原因异常
if (cause == this)
throw new IllegalArgumentException("Self-causation not permitted");
// 记录原因异常
this.cause = cause;
return this;
}


/** 原生方法,将当前线程的堆栈内容记录在本异常的追踪信息中 */
public synchronized native Throwable fillInStackTrace();


关于异常链的一个例子

class HighLevelException extends Exception{
public HighLevelException(Throwable cause) {
super(cause);
}
}

class MiddleLevelException extends Exception{
public MiddleLevelException(Throwable cause) {
super(cause);
}
}

class LowLevelException extends Exception{
}

public class TestException {

public void highLevelAccess() throws HighLevelException{
try {
middleLevelAccess();
} catch (Exception e) {
throw new HighLevelException(e);
}
}

public void middleLevelAccess() throws MiddleLevelException{
try {
lowLevelAccess();
} catch (Exception e) {
throw new MiddleLevelException(e);
}
}

public void lowLevelAccess() throws LowLevelException {
throw new LowLevelException();
}

public static void main(String[] args) {
try {
new TestException().highLevelAccess();
} catch (HighLevelException e) {
e.printStackTrace();
}
}
}


错误信息

test.HighLevelException: test.MiddleLevelException: test.LowLevelException
at test.TestException.highLevelAccess(TestException.java:24)
at test.TestException.main(TestException.java:42)
Caused by: test.MiddleLevelException: test.LowLevelException
at test.TestException.middleLevelAccess(TestException.java:32)
at test.TestException.highLevelAccess(TestException.java:22)
... 1 more
Caused by: test.LowLevelException
at test.TestException.lowLevelAccess(TestException.java:37)
at test.TestException.middleLevelAccess(TestException.java:30)
... 2 more
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值