1 /*
   2  * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 import  java.io.*;
  28 import  java.util.*;
  29 
  30 /**
  31  * The <code>Throwable</code> class is the superclass of all errors and
  32  * exceptions in the Java language. Only objects that are instances of this
  33  * class (or one of its subclasses) are thrown by the Java Virtual Machine or
  34  * can be thrown by the Java <code>throw</code> statement. Similarly, only
  35  * this class or one of its subclasses can be the argument type in a
  36  * <code>catch</code> clause.
  37  *
  38  * For the purposes of compile-time checking of exceptions, {@code
  39  * Throwable} and any subclass of {@code Throwable} that is not also a
  40  * subclass of either {@link RuntimeException} or {@link Error} are
  41  * regarded as checked exceptions.
  42  *
  43  * <p>Instances of two subclasses, {@link java.lang.Error} and
  44  * {@link java.lang.Exception}, are conventionally used to indicate
  45  * that exceptional situations have occurred. Typically, these instances
  46  * are freshly created in the context of the exceptional situation so
  47  * as to include relevant information (such as stack trace data).
  48  *
  49  * <p>A throwable contains a snapshot of the execution stack of its thread at
  50  * the time it was created. It can also contain a message string that gives
  51  * more information about the error. Finally, it can contain a <i>cause</i>:
  52  * another throwable that caused this throwable to get thrown.  The cause
  53  * facility is new in release 1.4.  It is also known as the <i>chained
  54  * exception</i> facility, as the cause can, itself, have a cause, and so on,
  55  * leading to a "chain" of exceptions, each caused by another.
  56  *
  57  * <p>One reason that a throwable may have a cause is that the class that
  58  * throws it is built atop a lower layered abstraction, and an operation on
  59  * the upper layer fails due to a failure in the lower layer.  It would be bad
  60  * design to let the throwable thrown by the lower layer propagate outward, as
  61  * it is generally unrelated to the abstraction provided by the upper layer.
  62  * Further, doing so would tie the API of the upper layer to the details of
  63  * its implementation, assuming the lower layer's exception was a checked
  64  * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
  65  * cause) allows the upper layer to communicate the details of the failure to
  66  * its caller without incurring either of these shortcomings.  It preserves
  67  * the flexibility to change the implementation of the upper layer without
  68  * changing its API (in particular, the set of exceptions thrown by its
  69  * methods).
  70  *
  71  * <p>A second reason that a throwable may have a cause is that the method
  72  * that throws it must conform to a general-purpose interface that does not
  73  * permit the method to throw the cause directly.  For example, suppose
  74  * a persistent collection conforms to the {@link java.util.Collection
  75  * Collection} interface, and that its persistence is implemented atop
  76  * <tt>java.io</tt>.  Suppose the internals of the <tt>add</tt> method
  77  * can throw an {@link java.io.IOException IOException}.  The implementation
  78  * can communicate the details of the <tt>IOException</tt> to its caller
  79  * while conforming to the <tt>Collection</tt> interface by wrapping the
  80  * <tt>IOException</tt> in an appropriate unchecked exception.  (The
  81  * specification for the persistent collection should indicate that it is
  82  * capable of throwing such exceptions.)
  83  *
  84  * <p>A cause can be associated with a throwable in two ways: via a
  85  * constructor that takes the cause as an argument, or via the
  86  * {@link #initCause(Throwable)} method.  New throwable classes that
  87  * wish to allow causes to be associated with them should provide constructors
  88  * that take a cause and delegate (perhaps indirectly) to one of the
  89  * <tt>Throwable</tt> constructors that takes a cause.  For example:
  90  * <pre>
  91  *     try {
  92  *         lowLevelOp();
  93  *     } catch (LowLevelException le) {
  94  *         throw new HighLevelException(le);  // Chaining-aware constructor
  95  *     }
  96  * </pre>
  97  * Because the <tt>initCause</tt> method is public, it allows a cause to be
  98  * associated with any throwable, even a "legacy throwable" whose
  99  * implementation predates the addition of the exception chaining mechanism to
 100  * <tt>Throwable</tt>. For example:
 101  * <pre>
 102  *     try {
 103  *         lowLevelOp();
 104  *     } catch (LowLevelException le) {
 105  *         throw (HighLevelException)
 106  *               new HighLevelException().initCause(le);  // Legacy constructor
 107  *     }
 108  * </pre>
 109  *
 110  * <p>Prior to release 1.4, there were many throwables that had their own
 111  * non-standard exception chaining mechanisms (
 112  * {@link ExceptionInInitializerError}, {@link ClassNotFoundException},
 113  * {@link java.lang.reflect.UndeclaredThrowableException},
 114  * {@link java.lang.reflect.InvocationTargetException},
 115  * {@link java.io.WriteAbortedException},
 116  * {@link java.security.PrivilegedActionException},
 117  * {@link java.awt.print.PrinterIOException},
 118  * {@link java.rmi.RemoteException} and
 119  * {@link javax.naming.NamingException}).
 120  * All of these throwables have been retrofitted to
 121  * use the standard exception chaining mechanism, while continuing to
 122  * implement their "legacy" chaining mechanisms for compatibility.
 123  *
 124  * <p>Further, as of release 1.4, many general purpose <tt>Throwable</tt>
 125  * classes (for example {@link Exception}, {@link RuntimeException},
 126  * {@link Error}) have been retrofitted with constructors that take
 127  * a cause.  This was not strictly necessary, due to the existence of the
 128  * <tt>initCause</tt> method, but it is more convenient and expressive to
 129  * delegate to a constructor that takes a cause.
 130  *
 131  * <p>By convention, class <code>Throwable</code> and its subclasses have two
 132  * constructors, one that takes no arguments and one that takes a
 133  * <code>String</code> argument that can be used to produce a detail message.
 134  * Further, those subclasses that might likely have a cause associated with
 135  * them should have two more constructors, one that takes a
 136  * <code>Throwable</code> (the cause), and one that takes a
 137  * <code>String</code> (the detail message) and a <code>Throwable</code> (the
 138  * cause).
 139  *
 140  * <p>Also introduced in release 1.4 is the {@link #getStackTrace()} method,
 141  * which allows programmatic access to the stack trace information that was
 142  * previously available only in text form, via the various forms of the
 143  * {@link #printStackTrace()} method.  This information has been added to the
 144  * <i>serialized representation</i> of this class so <tt>getStackTrace</tt>
 145  * and <tt>printStackTrace</tt> will operate properly on a throwable that
 146  * was obtained by deserialization.
 147  *
 148  * @author  unascribed
 149  * @author  Josh Bloch (Added exception chaining and programmatic access to
 150  *          stack trace in 1.4.)
 151  * @jls3 11.2 Compile-Time Checking of Exceptions
 152  * @since JDK1.0
 153  */
 154 public class Throwable implements Serializable {
 155     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 156     private static final long serialVersionUID = -3042686055658047285L;
 157 
 158     /**
 159      * Native code saves some indication of the stack backtrace in this slot.
 160      */
 161     private transient Object backtrace;
 162 
 163     /**
 164      * Specific details about the Throwable.  For example, for
 165      * <tt>FileNotFoundException</tt>, this contains the name of
 166      * the file that could not be found.
 167      *
 168      * @serial
 169      */
 170     private String detailMessage;
 171 
 172     /**
 173      * The throwable that caused this throwable to get thrown, or null if this
 174      * throwable was not caused by another throwable, or if the causative
 175      * throwable is unknown.  If this field is equal to this throwable itself,
 176      * it indicates that the cause of this throwable has not yet been
 177      * initialized.
 178      *
 179      * @serial
 180      * @since 1.4
 181      */
 182     private Throwable cause = this;
 183 
 184     /**
 185      * The stack trace, as returned by {@link #getStackTrace()}.
 186      *
 187      * @serial
 188      * @since 1.4
 189      */
 190     private StackTraceElement[] stackTrace;
 191     /*
 192      * This field is lazily initialized on first use or serialization and
 193      * nulled out when fillInStackTrace is called.
 194      */
 195 
 196     /**
 197      * The list of suppressed exceptions, as returned by
 198      * {@link #getSuppressedExceptions()}.
 199      *
 200      * @serial
 201      * @since 1.7
 202      */
 203     private List<Throwable> suppressedExceptions = Collections.emptyList();
 204 
 205     /** Message for trying to suppress a null exception. */
 206     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
 207 
 208     /** Caption  for labeling causative exception stack traces */
 209     private static final String CAUSE_CAPTION = "Caused by: ";
 210 
 211     /** Caption for labeling suppressed exception stack traces */
 212     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
 213 
 214     /**
 215      * Constructs a new throwable with <code>null</code> as its detail message.
 216      * The cause is not initialized, and may subsequently be initialized by a
 217      * call to {@link #initCause}.
 218      *
 219      * <p>The {@link #fillInStackTrace()} method is called to initialize
 220      * the stack trace data in the newly created throwable.
 221      */
 222     public Throwable() {
 223         fillInStackTrace();
 224     }
 225 
 226     /**
 227      * Constructs a new throwable with the specified detail message.  The
 228      * cause is not initialized, and may subsequently be initialized by
 229      * a call to {@link #initCause}.
 230      *
 231      * <p>The {@link #fillInStackTrace()} method is called to initialize
 232      * the stack trace data in the newly created throwable.
 233      *
 234      * @param   message   the detail message. The detail message is saved for
 235      *          later retrieval by the {@link #getMessage()} method.
 236      */
 237     public Throwable(String message) {
 238         fillInStackTrace();
 239         detailMessage = message;
 240     }
 241 
 242     /**
 243      * Constructs a new throwable with the specified detail message and
 244      * cause.  <p>Note that the detail message associated with
 245      * <code>cause</code> is <i>not</i> automatically incorporated in
 246      * this throwable's detail message.
 247      *
 248      * <p>The {@link #fillInStackTrace()} method is called to initialize
 249      * the stack trace data in the newly created throwable.
 250      *
 251      * @param  message the detail message (which is saved for later retrieval
 252      *         by the {@link #getMessage()} method).
 253      * @param  cause the cause (which is saved for later retrieval by the
 254      *         {@link #getCause()} method).  (A <tt>null</tt> value is
 255      *         permitted, and indicates that the cause is nonexistent or
 256      *         unknown.)
 257      * @since  1.4
 258      */
 259     public Throwable(String message, Throwable cause) {
 260         fillInStackTrace();
 261         detailMessage = message;
 262         this.cause = cause;
 263     }
 264 
 265     /**
 266      * Constructs a new throwable with the specified cause and a detail
 267      * message of <tt>(cause==null ? null : cause.toString())</tt> (which
 268      * typically contains the class and detail message of <tt>cause</tt>).
 269      * This constructor is useful for throwables that are little more than
 270      * wrappers for other throwables (for example, {@link
 271      * java.security.PrivilegedActionException}).
 272      *
 273      * <p>The {@link #fillInStackTrace()} method is called to initialize
 274      * the stack trace data in the newly created throwable.
 275      *
 276      * @param  cause the cause (which is saved for later retrieval by the
 277      *         {@link #getCause()} method).  (A <tt>null</tt> value is
 278      *         permitted, and indicates that the cause is nonexistent or
 279      *         unknown.)
 280      * @since  1.4
 281      */
 282     public Throwable(Throwable cause) {
 283         fillInStackTrace();
 284         detailMessage = (cause==null ? null : cause.toString());
 285         this.cause = cause;
 286     }
 287 
 288     /**
 289      * Returns the detail message string of this throwable.
 290      *
 291      * @return  the detail message string of this <tt>Throwable</tt> instance
 292      *          (which may be <tt>null</tt>).
 293      */
 294     public String getMessage() {
 295         return detailMessage;
 296     }
 297 
 298     /**
 299      * Creates a localized description of this throwable.
 300      * Subclasses may override this method in order to produce a
 301      * locale-specific message.  For subclasses that do not override this
 302      * method, the default implementation returns the same result as
 303      * <code>getMessage()</code>.
 304      *
 305      * @return  The localized description of this throwable.
 306      * @since   JDK1.1
 307      */
 308     public String getLocalizedMessage() {
 309         return getMessage();
 310     }
 311 
 312     /**
 313      * Returns the cause of this throwable or <code>null</code> if the
 314      * cause is nonexistent or unknown.  (The cause is the throwable that
 315      * caused this throwable to get thrown.)
 316      *
 317      * <p>This implementation returns the cause that was supplied via one of
 318      * the constructors requiring a <tt>Throwable</tt>, or that was set after
 319      * creation with the {@link #initCause(Throwable)} method.  While it is
 320      * typically unnecessary to override this method, a subclass can override
 321      * it to return a cause set by some other means.  This is appropriate for
 322      * a "legacy chained throwable" that predates the addition of chained
 323      * exceptions to <tt>Throwable</tt>.  Note that it is <i>not</i>
 324      * necessary to override any of the <tt>PrintStackTrace</tt> methods,
 325      * all of which invoke the <tt>getCause</tt> method to determine the
 326      * cause of a throwable.
 327      *
 328      * @return  the cause of this throwable or <code>null</code> if the
 329      *          cause is nonexistent or unknown.
 330      * @since 1.4
 331      */
 332     public Throwable getCause() {
 333         return (cause==this ? null : cause);
 334     }
 335 
 336     /**
 337      * Initializes the <i>cause</i> of this throwable to the specified value.
 338      * (The cause is the throwable that caused this throwable to get thrown.)
 339      *
 340      * <p>This method can be called at most once.  It is generally called from
 341      * within the constructor, or immediately after creating the
 342      * throwable.  If this throwable was created
 343      * with {@link #Throwable(Throwable)} or
 344      * {@link #Throwable(String,Throwable)}, this method cannot be called
 345      * even once.
 346      *
 347      * @param  cause the cause (which is saved for later retrieval by the
 348      *         {@link #getCause()} method).  (A <tt>null</tt> value is
 349      *         permitted, and indicates that the cause is nonexistent or
 350      *         unknown.)
 351      * @return  a reference to this <code>Throwable</code> instance.
 352      * @throws IllegalArgumentException if <code>cause</code> is this
 353      *         throwable.  (A throwable cannot be its own cause.)
 354      * @throws IllegalStateException if this throwable was
 355      *         created with {@link #Throwable(Throwable)} or
 356      *         {@link #Throwable(String,Throwable)}, or this method has already
 357      *         been called on this throwable.
 358      * @since  1.4
 359      */
 360     public synchronized Throwable initCause(Throwable cause) {
 361         if (this.cause != this)
 362             throw new IllegalStateException("Can't overwrite cause");
 363         if (cause == this)
 364             throw new IllegalArgumentException("Self-causation not permitted");
 365         this.cause = cause;
 366         return this;
 367     }
 368 
 369     /**
 370      * Returns a short description of this throwable.
 371      * The result is the concatenation of:
 372      * <ul>
 373      * <li> the {@linkplain Class#getName() name} of the class of this object
 374      * <li> ": " (a colon and a space)
 375      * <li> the result of invoking this object's {@link #getLocalizedMessage}
 376      *      method
 377      * </ul>
 378      * If <tt>getLocalizedMessage</tt> returns <tt>null</tt>, then just
 379      * the class name is returned.
 380      *
 381      * @return a string representation of this throwable.
 382      */
 383     public String toString() {
 384         String s = getClass().getName();
 385         String message = getLocalizedMessage();
 386         return (message != null) ? (s + ": " + message) : s;
 387     }
 388 
 389     /**
 390      * Prints this throwable and its backtrace to the
 391      * standard error stream. This method prints a stack trace for this
 392      * <code>Throwable</code> object on the error output stream that is
 393      * the value of the field <code>System.err</code>. The first line of
 394      * output contains the result of the {@link #toString()} method for
 395      * this object.  Remaining lines represent data previously recorded by
 396      * the method {@link #fillInStackTrace()}. The format of this
 397      * information depends on the implementation, but the following
 398      * example may be regarded as typical:
 399      * <blockquote><pre>
 400      * java.lang.NullPointerException
 401      *         at MyClass.mash(MyClass.java:9)
 402      *         at MyClass.crunch(MyClass.java:6)
 403      *         at MyClass.main(MyClass.java:3)
 404      * </pre></blockquote>
 405      * This example was produced by running the program:
 406      * <pre>
 407      * class MyClass {
 408      *     public static void main(String[] args) {
 409      *         crunch(null);
 410      *     }
 411      *     static void crunch(int[] a) {
 412      *         mash(a);
 413      *     }
 414      *     static void mash(int[] b) {
 415      *         System.out.println(b[0]);
 416      *     }
 417      * }
 418      * </pre>
 419      * The backtrace for a throwable with an initialized, non-null cause
 420      * should generally include the backtrace for the cause.  The format
 421      * of this information depends on the implementation, but the following
 422      * example may be regarded as typical:
 423      * <pre>
 424      * HighLevelException: MidLevelException: LowLevelException
 425      *         at Junk.a(Junk.java:13)
 426      *         at Junk.main(Junk.java:4)
 427      * Caused by: MidLevelException: LowLevelException
 428      *         at Junk.c(Junk.java:23)
 429      *         at Junk.b(Junk.java:17)
 430      *         at Junk.a(Junk.java:11)
 431      *         ... 1 more
 432      * Caused by: LowLevelException
 433      *         at Junk.e(Junk.java:30)
 434      *         at Junk.d(Junk.java:27)
 435      *         at Junk.c(Junk.java:21)
 436      *         ... 3 more
 437      * </pre>
 438      * Note the presence of lines containing the characters <tt>"..."</tt>.
 439      * These lines indicate that the remainder of the stack trace for this
 440      * exception matches the indicated number of frames from the bottom of the
 441      * stack trace of the exception that was caused by this exception (the
 442      * "enclosing" exception).  This shorthand can greatly reduce the length
 443      * of the output in the common case where a wrapped exception is thrown
 444      * from same method as the "causative exception" is caught.  The above
 445      * example was produced by running the program:
 446      * <pre>
 447      * public class Junk {
 448      *     public static void main(String args[]) {
 449      *         try {
 450      *             a();
 451      *         } catch(HighLevelException e) {
 452      *             e.printStackTrace();
 453      *         }
 454      *     }
 455      *     static void a() throws HighLevelException {
 456      *         try {
 457      *             b();
 458      *         } catch(MidLevelException e) {
 459      *             throw new HighLevelException(e);
 460      *         }
 461      *     }
 462      *     static void b() throws MidLevelException {
 463      *         c();
 464      *     }
 465      *     static void c() throws MidLevelException {
 466      *         try {
 467      *             d();
 468      *         } catch(LowLevelException e) {
 469      *             throw new MidLevelException(e);
 470      *         }
 471      *     }
 472      *     static void d() throws LowLevelException {
 473      *        e();
 474      *     }
 475      *     static void e() throws LowLevelException {
 476      *         throw new LowLevelException();
 477      *     }
 478      * }
 479      *
 480      * class HighLevelException extends Exception {
 481      *     HighLevelException(Throwable cause) { super(cause); }
 482      * }
 483      *
 484      * class MidLevelException extends Exception {
 485      *     MidLevelException(Throwable cause)  { super(cause); }
 486      * }
 487      *
 488      * class LowLevelException extends Exception {
 489      * }
 490      * </pre>
 491      * As of release 7, the platform supports the notion of
 492      * <i>suppressed exceptions</i> (in conjunction with automatic
 493      * resource management blocks). Any exceptions that were
 494      * suppressed in order to deliver an exception are printed out
 495      * beneath the stack trace.  The format of this information
 496      * depends on the implementation, but the following example may be
 497      * regarded as typical:
 498      *
 499      * <pre>
 500      * Exception in thread "main" java.lang.Exception: Something happened
 501      *  at Foo.bar(Foo.java:10)
 502      *  at Foo.main(Foo.java:5)
 503      *  Suppressed: Resource$CloseFailException: Resource ID = 0
 504      *          at Resource.close(Resource.java:26)
 505      *          at Foo.bar(Foo.java:9)
 506      *          ... 1 more
 507      * </pre>
 508      * Note that the "... n more" notation is used on suppressed exceptions
 509      * just at it is used on causes. Unlike causes, suppressed exceptions are
 510      * indented beyond their "containing exceptions."
 511      *
 512      * <p>An exception can have both a cause and one or more suppressed
 513      * exceptions:
 514      * <pre>
 515      * Exception in thread "main" java.lang.Exception: Main block
 516      *  at Foo3.main(Foo3.java:7)
 517      *  Suppressed: Resource$CloseFailException: Resource ID = 2
 518      *          at Resource.close(Resource.java:26)
 519      *          at Foo3.main(Foo3.java:5)
 520      *  Suppressed: Resource$CloseFailException: Resource ID = 1
 521      *          at Resource.close(Resource.java:26)
 522      *          at Foo3.main(Foo3.java:5)
 523      * Caused by: java.lang.Exception: I did it
 524      *  at Foo3.main(Foo3.java:8)
 525      * </pre>
 526      * Likewise, a suppressed exception can have a cause:
 527      * <pre>
 528      * Exception in thread "main" java.lang.Exception: Main block
 529      *  at Foo4.main(Foo4.java:6)
 530      *  Suppressed: Resource2$CloseFailException: Resource ID = 1
 531      *          at Resource2.close(Resource2.java:20)
 532      *          at Foo4.main(Foo4.java:5)
 533      *  Caused by: java.lang.Exception: Rats, you caught me
 534      *          at Resource2$CloseFailException.<init>(Resource2.java:45)
 535      *          ... 2 more
 536      * </pre>
 537      */
 538     public void printStackTrace() {
 539         printStackTrace(System.err);
 540     }
 541 
 542     /**
 543      * Prints this throwable and its backtrace to the specified print stream.
 544      *
 545      * @param s <code>PrintStream</code> to use for output
 546      */
 547     public void printStackTrace(PrintStream s) {
 548         printStackTrace(new WrappedPrintStream(s));
 549     }
 550 
 551     private void printStackTrace(PrintStreamOrWriter s) {
 552         Set<Throwable> dejaVu = new HashSet<Throwable>();
 553         dejaVu.add(this);
 554 
 555         synchronized (s.lock()) {
 556             // Print our stack trace
 557             s.println(this);
 558             StackTraceElement[] trace = getOurStackTrace();
 559             for (StackTraceElement traceElement : trace)
 560                 s.println("\tat " + traceElement);
 561 
 562             // Print suppressed exceptions, if any
 563             for (Throwable se : suppressedExceptions)
 564                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
 565 
 566             // Print cause, if any
 567             Throwable ourCause = getCause();
 568             if (ourCause != null)
 569                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
 570         }
 571     }
 572 
 573     /**
 574      * Print our stack trace as an enclosed exception for the specified
 575      * stack trace.
 576      */
 577     private void printEnclosedStackTrace(PrintStreamOrWriter s,
 578                                          StackTraceElement[] enclosingTrace,
 579                                          String caption,
 580                                          String prefix,
 581                                          Set<Throwable> dejaVu) {
 582         assert Thread.holdsLock(s.lock());
 583         if (dejaVu.contains(this)) {
 584             s.println("\t[CIRCULAR REFERENCE:" + this + "]");
 585         } else {
 586             dejaVu.add(this);
 587             // Compute number of frames in common between this and enclosing trace
 588             StackTraceElement[] trace = getOurStackTrace();
 589             int m = trace.length - 1;
 590             int n = enclosingTrace.length - 1;
 591             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
 592                 m--; n--;
 593             }
 594             int framesInCommon = trace.length - 1 - m;
 595 
 596             // Print our stack trace
 597             s.println(prefix + caption + this);
 598             for (int i = 0; i <= m; i++)
 599                 s.println(prefix + "\tat " + trace[i]);
 600             if (framesInCommon != 0)
 601                 s.println(prefix + "\t... " + framesInCommon + " more");
 602 
 603             // Print suppressed exceptions, if any
 604             for (Throwable se : suppressedExceptions)
 605                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
 606                                            prefix +"\t", dejaVu);
 607 
 608             // Print cause, if any
 609             Throwable ourCause = getCause();
 610             if (ourCause != null)
 611                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
 612         }
 613     }
 614 
 615     /**
 616      * Prints this throwable and its backtrace to the specified
 617      * print writer.
 618      *
 619      * @param s <code>PrintWriter</code> to use for output
 620      * @since   JDK1.1
 621      */
 622     public void printStackTrace(PrintWriter s) {
 623         printStackTrace(new WrappedPrintWriter(s));
 624     }
 625 
 626     /**
 627      * Wrapper class for PrintStream and PrintWriter to enable a single
 628      * implementation of printStackTrace.
 629      */
 630     private abstract static class PrintStreamOrWriter {
 631         /** Returns the object to be locked when using this StreamOrWriter */
 632         abstract Object lock();
 633 
 634         /** Prints the specified string as a line on this StreamOrWriter */
 635         abstract void println(Object o);
 636     }
 637 
 638     private static class WrappedPrintStream extends PrintStreamOrWriter {
 639         private final PrintStream printStream;
 640 
 641         WrappedPrintStream(PrintStream printStream) {
 642             this.printStream = printStream;
 643         }
 644 
 645         Object lock() {
 646             return printStream;
 647         }
 648 
 649         void println(Object o) {
 650             printStream.println(o);
 651         }
 652     }
 653 
 654     private static class WrappedPrintWriter extends PrintStreamOrWriter {
 655         private final PrintWriter printWriter;
 656 
 657         WrappedPrintWriter(PrintWriter printWriter) {
 658             this.printWriter = printWriter;
 659         }
 660 
 661         Object lock() {
 662             return printWriter;
 663         }
 664 
 665         void println(Object o) {
 666             printWriter.println(o);
 667         }
 668     }
 669 
 670     /**
 671      * Fills in the execution stack trace. This method records within this
 672      * <code>Throwable</code> object information about the current state of
 673      * the stack frames for the current thread.
 674      *
 675      * @return  a reference to this <code>Throwable</code> instance.
 676      * @see     java.lang.Throwable#printStackTrace()
 677      */
 678     public synchronized native Throwable fillInStackTrace();
 679 
 680     /**
 681      * Provides programmatic access to the stack trace information printed by
 682      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
 683      * each representing one stack frame.  The zeroth element of the array
 684      * (assuming the array's length is non-zero) represents the top of the
 685      * stack, which is the last method invocation in the sequence.  Typically,
 686      * this is the point at which this throwable was created and thrown.
 687      * The last element of the array (assuming the array's length is non-zero)
 688      * represents the bottom of the stack, which is the first method invocation
 689      * in the sequence.
 690      *
 691      * <p>Some virtual machines may, under some circumstances, omit one
 692      * or more stack frames from the stack trace.  In the extreme case,
 693      * a virtual machine that has no stack trace information concerning
 694      * this throwable is permitted to return a zero-length array from this
 695      * method.  Generally speaking, the array returned by this method will
 696      * contain one element for every frame that would be printed by
 697      * <tt>printStackTrace</tt>.
 698      *
 699      * @return an array of stack trace elements representing the stack trace
 700      *         pertaining to this throwable.
 701      * @since  1.4
 702      */
 703     public StackTraceElement[] getStackTrace() {
 704         return getOurStackTrace().clone();
 705     }
 706 
 707     private synchronized StackTraceElement[] getOurStackTrace() {
 708         // Initialize stack trace if this is the first call to this method
 709         if (stackTrace == null) {
 710             int depth = getStackTraceDepth();
 711             stackTrace = new StackTraceElement[depth];
 712             for (int i=0; i < depth; i++)
 713                 stackTrace[i] = getStackTraceElement(i);
 714         }
 715         return stackTrace;
 716     }
 717 
 718     /**
 719      * Sets the stack trace elements that will be returned by
 720      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
 721      * and related methods.
 722      *
 723      * This method, which is designed for use by RPC frameworks and other
 724      * advanced systems, allows the client to override the default
 725      * stack trace that is either generated by {@link #fillInStackTrace()}
 726      * when a throwable is constructed or deserialized when a throwable is
 727      * read from a serialization stream.
 728      *
 729      * @param   stackTrace the stack trace elements to be associated with
 730      * this <code>Throwable</code>.  The specified array is copied by this
 731      * call; changes in the specified array after the method invocation
 732      * returns will have no affect on this <code>Throwable</code>'s stack
 733      * trace.
 734      *
 735      * @throws NullPointerException if <code>stackTrace</code> is
 736      *         <code>null</code>, or if any of the elements of
 737      *         <code>stackTrace</code> are <code>null</code>
 738      *
 739      * @since  1.4
 740      */
 741     public void setStackTrace(StackTraceElement[] stackTrace) {
 742         StackTraceElement[] defensiveCopy = stackTrace.clone();
 743         for (int i = 0; i < defensiveCopy.length; i++)
 744             if (defensiveCopy[i] == null)
 745                 throw new NullPointerException("stackTrace[" + i + "]");
 746 
 747         this.stackTrace = defensiveCopy;
 748     }
 749 
 750     /**
 751      * Returns the number of elements in the stack trace (or 0 if the stack
 752      * trace is unavailable).
 753      *
 754      * package-protection for use by SharedSecrets.
 755      */
 756     native int getStackTraceDepth();
 757 
 758     /**
 759      * Returns the specified element of the stack trace.
 760      *
 761      * package-protection for use by SharedSecrets.
 762      *
 763      * @param index index of the element to return.
 764      * @throws IndexOutOfBoundsException if <tt>index &lt; 0 ||
 765      *         index &gt;= getStackTraceDepth() </tt>
 766      */
 767     native StackTraceElement getStackTraceElement(int index);
 768 
 769     private void readObject(ObjectInputStream s)
 770         throws IOException, ClassNotFoundException {
 771         s.defaultReadObject();     // read in all fields
 772         List<Throwable> suppressed = Collections.emptyList();
 773         if (suppressedExceptions != null &&
 774             !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
 775             suppressed = new ArrayList<Throwable>();
 776             for(Throwable t : suppressedExceptions) {
 777                 if (t == null)
 778                     throw new NullPointerException(NULL_CAUSE_MESSAGE);
 779                 suppressed.add(t);
 780             }
 781         }
 782         suppressedExceptions = suppressed;
 783     }
 784 
 785     private synchronized void writeObject(ObjectOutputStream s)
 786         throws IOException
 787     {
 788         getOurStackTrace();  // Ensure that stackTrace field is initialized.
 789         s.defaultWriteObject();
 790     }
 791 
 792     /**
 793      * Adds the specified exception to the list of exceptions that
 794      * were suppressed, typically by the automatic resource management
 795      * statement, in order to deliver this exception.
 796      *
 797      * @param exception the exception to be added to the list of
 798      *        suppressed exceptions
 799      * @throws NullPointerException if {@code exception} is null
 800      * @since 1.7
 801      */
 802     public synchronized void addSuppressedException(Throwable exception) {
 803         if (exception == null)
 804             throw new NullPointerException(NULL_CAUSE_MESSAGE);
 805 
 806         if (suppressedExceptions.size() == 0)
 807             suppressedExceptions = new ArrayList<Throwable>();
 808         suppressedExceptions.add(exception);
 809     }
 810 
 811     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 812 
 813     /**
 814      * Returns an array containing all of the exceptions that were
 815      * suppressed, typically by the automatic resource management
 816      * statement, in order to deliver this exception.
 817      *
 818      * @return an array containing all of the exceptions that were
 819      *         suppressed to deliver this exception.
 820      * @since 1.7
 821      */
 822     public Throwable[] getSuppressedExceptions() {
 823         return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 824     }
 825 }