// 由native方法赋值,用来保存栈信息的轨迹 // The JVM saves some indication of the stack backtrace in this slot. privatetransient Object backtrace; // The JVM code sets the depth of the backtrace for later retrieval privatetransientint depth; // 异常描述信息,如RuntimeException("File Not Found"),其中字符串"File Not Found"就是异常描述信息 private String detailMessage; // 记录当前异常是由哪个异常所引起的,默认是this,可通过构造器自定义,也可以通过initCase方法进行修改 privateThrowablecause=this; // 引起异常的堆栈跟踪信息,初始化为零长度数组,该字段为null意味着随后setStackTrace(StackTraceElement[])和fillInStackTrace()方法什么也不做 privatestaticfinal StackTraceElement[] UNASSIGNED_STACK = newStackTraceElement[0]; private StackTraceElement[] stackTrace = UNASSIGNED_STACK; // 该列表初始化为零元素不可修改的哨兵列表。读入序列化的Throwable时,如果suppressedExceptions字段指向零元素列表,则该字段将重置为哨兵值(SUPPRESSED_SENTINEL)。 privatestaticfinal List<Throwable> SUPPRESSED_SENTINEL = Collections.emptyList(); private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
public StackTraceElement[] getStackTrace() { return getOurStackTrace().clone(); }
privatesynchronized StackTraceElement[] getOurStackTrace() { // Initialize stack trace field with information from // backtrace if this is the first call to this method if (stackTrace == UNASSIGNED_STACK || (stackTrace == null && backtrace != null) /* Out of protocol state */) { stackTrace = StackTraceElement.of(this, depth); } elseif (stackTrace == null) { return UNASSIGNED_STACK; } return stackTrace; }
static StackTraceElement[] of(Throwable x, int depth) { // 创建栈追踪信息数组 StackTraceElement[] stackTrace = newStackTraceElement[depth]; for (inti=0; i < depth; i++) { stackTrace[i] = newStackTraceElement(); }
// VM to fill in StackTraceElement // 利用给定Throwable类的backtrace字段设置栈追踪信息数组元素,本地方法 initStackTraceElements(stackTrace, x);
// ensure the proper StackTraceElement initialization for (StackTraceElement ste : stackTrace) { ste.computeFormat(); } return stackTrace; }
privatestaticfinalStringSELF_SUPPRESSION_MESSAGE="Self-suppression not permitted"; privatestaticfinalStringNULL_CAUSE_MESSAGE="Cannot suppress a null exception.";
publicfinalsynchronizedvoidaddSuppressed(Throwable exception) { // 附加的exception不能为自身 if (exception == this) thrownewIllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception); // 附加的exception不能为null if (exception == null) thrownewNullPointerException(NULL_CAUSE_MESSAGE); // 不允许设置suppressedExceptions if (suppressedExceptions == null) // Suppressed exceptions not recorded return; // suppressedExceptions初始化 if (suppressedExceptions == SUPPRESSED_SENTINEL) suppressedExceptions = newArrayList<>(1);
privatevoidprintStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. Set<Throwable> dejaVu = Collections.newSetFromMap(newIdentityHashMap<>()); dejaVu.add(this);