import java.io.*; public class Throwable implements Serializable ...{ /** *//** use serialVersionUID from JDK 1.0.2 for interOperability */ PRivate static final long serialVersionUID = -3042686055658047285L; /** *//** * Native code saves some indication of the stack backtrace in this slot. */ private transient Object backtrace; private String detailMessage; private Throwable cause = this; private StackTraceElement[] stackTrace; public Throwable() ...{ fillInStackTrace(); } public Throwable(String message) ...{ fillInStackTrace(); detailMessage = message; } public Throwable(String message, Throwable cause) ...{ fillInStackTrace(); detailMessage = message; this.cause = cause; } public String getLocalizedMessage() ...{ return getMessage(); } 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"); if (cause == this) throw new IllegalArgumentException("Self-causation not permitted"); this.cause = cause; return this; } public String toString() ...{ String s = getClass().getName(); String message = getLocalizedMessage(); return (message != null) ? (s + ": " + message) : s; } private synchronized StackTraceElement[] getOurStackTrace() ...{ // Initialize stack trace if this is the first call to this method if (stackTrace == null) ...{ int depth = getStackTraceDepth(); stackTrace = new StackTraceElement[depth]; for (int i=0; i < depth; i++) stackTrace[i] = getStackTraceElement(i); } return stackTrace; } //......省略了一些 }
注重一点:异常类是可串行化的。
public class Exception extends Throwable { static final long serialVersionUID = -3387516993124229948L;
public Exception() { super(); }
public Exception(String message) { super(message); }
public Exception(String message, Throwable cause) { super(message, cause); }
public Exception(Throwable cause) { super(cause); } }
一个简单例子:
public class MyException extends Exception ...{ MyException(String str) ...{ super(str); } } public class MyTest ...{ public void f()throws MyException ...{ throw new MyException("f() exception"); } } public class Main ...{ public static void main(String[]args) ...{ try ...{ new MyTest().f(); }catch(MyException me) ...{ System.out.println(me); }finally ...{System.out.println("finally"); } } }