Throwable源码异常分析

问题:

Throwable是所有异常的父类,那么异常到底包含哪些信息呢?

1.Throwable包含哪些成员变量?

public class Throwable implements Serializable {
    private transient volatile Object backtrace;
    //异常信息
    private String detailMessage;
    //当前异常是由哪个Throwable所引起的
    private Throwable cause = this;
    //引起异常的堆栈跟踪信息
    private StackTraceElement[] stackTrace = libcore.util.EmptyArray.STACK_TRACE_ELEMENT;
}

backtrace:这个变量由native方法赋值,用来保存栈信息的轨迹;

detailMessage:这个变量是描述异常信息,比如new  InsertFailException("can't insert table"),记录的是传进去描述此异常的描述信息"can't insert table";

case:记录当前异常是由哪个异常所引起的,默认是this,可通过构造器自定义;可以通过initCase方法进行修改:

public synchronized Throwable initCause(Throwable cause) {
        if (this.cause != this)
            throw new IllegalStateException("Can't overwrite cause with " +
                                            Objects.toString(cause, "a null"), this);
        if (cause == this)
            throw new IllegalArgumentException("Self-causation not permitted", this);
        this.cause = cause;
        return this;
    }

可以看到case只能被修改一次,当发现case已经被修改,则会抛出IllegalStateException异常;默认case=this,如果再次修改case为this也是不允许的;

case一般这样使用:

      try {
          lowLevelOp();
      } catch (LowLevelException le) {
          throw (HighLevelException)
                new HighLevelException().initCause(le); // Legacy constructor
      }

stackTrace:记录当前异常堆栈信息,数组中每一个StackTraceElement表示当前方法调用的一个栈帧,表示一次方法调用;StackTraceElement中保存的有当前方法的类名,方法名,文件名,行号信息;

public final class StackTraceElement implements java.io.Serializable {
    // Normally initialized by VM (public constructor added in 1.5)
    private String declaringClass;
    private String methodName;
    private String fileName;
    private int    lineNumber;
    
    public String toString() {
        // Android-changed: When ART cannot find a line number, the lineNumber field is set
        // to the dex_pc and the fileName field is set to null.
        StringBuilder result = new StringBuilder();
        result.append(getClassName()).append(".").append(methodName);
        if (isNativeMethod()) {
            result.append("(Native Method)");
        } else if (fileName != null) {
            if (lineNumber >= 0) {
                result.append("(").append(fileName).append(":").append(lineNumber).append(")");
            } else {
                result.append("(").append(fileName).append(")");
            }
        } else {
            if (lineNumber >= 0) {
                // The line number is actually the dex pc.
                result.append("(Unknown Source:").append(lineNumber).append(")&#
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值