问题:
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(")&#