src/share/classes/java/lang/Throwable.java

Print this page




  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()}.


 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      *     }


 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) {


 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 


 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;


 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     }


  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} 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} statement. Similarly, only
  35  * this class or one of its subclasses can be the argument type in a
  36  * {@code catch} 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  * {@code java.io}.  Suppose the internals of the {@code add} method
  77  * can throw an {@link java.io.IOException IOException}.  The implementation
  78  * can communicate the details of the {@code IOException} to its caller
  79  * while conforming to the {@code Collection} interface by wrapping the
  80  * {@code IOException} 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  * {@code Throwable} 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 {@code initCause} 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  * {@code Throwable}. 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 {@code Throwable}
 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  * {@code initCause} 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} and its subclasses have two
 132  * constructors, one that takes no arguments and one that takes a
 133  * {@code String} 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} (the cause), and one that takes a
 137  * {@code String} (the detail message) and a {@code Throwable} (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 {@code getStackTrace}
 145  * and {@code printStackTrace} 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      * {@code FileNotFoundException}, 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()}.


 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} 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} 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 {@code null} 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 {@code (cause==null ? null : cause.toString())} (which
 268      * typically contains the class and detail message of {@code cause}).
 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 {@code null} 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 {@code Throwable} instance
 292      *          (which may be {@code null}).
 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()}.
 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} 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 {@code Throwable}, 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 {@code Throwable}.  Note that it is <i>not</i>
 324      * necessary to override any of the {@code PrintStackTrace} methods,
 325      * all of which invoke the {@code getCause} method to determine the
 326      * cause of a throwable.
 327      *
 328      * @return  the cause of this throwable or {@code null} 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 {@code null} value is
 349      *         permitted, and indicates that the cause is nonexistent or
 350      *         unknown.)
 351      * @return  a reference to this {@code Throwable} instance.
 352      * @throws IllegalArgumentException if {@code cause} 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 {@code getLocalizedMessage} returns {@code null}, 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} object on the error output stream that is
 393      * the value of the field {@code System.err}. 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      *     }


 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 {@code "..."}.
 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) {


 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} 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         // Guard against malicious overrides of Throwable.equals by
 553         // using a Set with identity equality semantics.
 554         Set<Throwable> dejaVu =
 555             Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
 556         dejaVu.add(this);
 557 
 558         synchronized (s.lock()) {
 559             // Print our stack trace
 560             s.println(this);
 561             StackTraceElement[] trace = getOurStackTrace();
 562             for (StackTraceElement traceElement : trace)
 563                 s.println("\tat " + traceElement);
 564 
 565             // Print suppressed exceptions, if any
 566             for (Throwable se : suppressedExceptions)
 567                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
 568 
 569             // Print cause, if any
 570             Throwable ourCause = getCause();
 571             if (ourCause != null)
 572                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
 573         }
 574     }
 575 


 602                 s.println(prefix + "\tat " + trace[i]);
 603             if (framesInCommon != 0)
 604                 s.println(prefix + "\t... " + framesInCommon + " more");
 605 
 606             // Print suppressed exceptions, if any
 607             for (Throwable se : suppressedExceptions)
 608                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
 609                                            prefix +"\t", dejaVu);
 610 
 611             // Print cause, if any
 612             Throwable ourCause = getCause();
 613             if (ourCause != null)
 614                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
 615         }
 616     }
 617 
 618     /**
 619      * Prints this throwable and its backtrace to the specified
 620      * print writer.
 621      *
 622      * @param s {@code PrintWriter} to use for output
 623      * @since   JDK1.1
 624      */
 625     public void printStackTrace(PrintWriter s) {
 626         printStackTrace(new WrappedPrintWriter(s));
 627     }
 628 
 629     /**
 630      * Wrapper class for PrintStream and PrintWriter to enable a single
 631      * implementation of printStackTrace.
 632      */
 633     private abstract static class PrintStreamOrWriter {
 634         /** Returns the object to be locked when using this StreamOrWriter */
 635         abstract Object lock();
 636 
 637         /** Prints the specified string as a line on this StreamOrWriter */
 638         abstract void println(Object o);
 639     }
 640 
 641     private static class WrappedPrintStream extends PrintStreamOrWriter {
 642         private final PrintStream printStream;


 655     }
 656 
 657     private static class WrappedPrintWriter extends PrintStreamOrWriter {
 658         private final PrintWriter printWriter;
 659 
 660         WrappedPrintWriter(PrintWriter printWriter) {
 661             this.printWriter = printWriter;
 662         }
 663 
 664         Object lock() {
 665             return printWriter;
 666         }
 667 
 668         void println(Object o) {
 669             printWriter.println(o);
 670         }
 671     }
 672 
 673     /**
 674      * Fills in the execution stack trace. This method records within this
 675      * {@code Throwable} object information about the current state of
 676      * the stack frames for the current thread.
 677      *
 678      * @return  a reference to this {@code Throwable} instance.
 679      * @see     java.lang.Throwable#printStackTrace()
 680      */
 681     public synchronized native Throwable fillInStackTrace();
 682 
 683     /**
 684      * Provides programmatic access to the stack trace information printed by
 685      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
 686      * each representing one stack frame.  The zeroth element of the array
 687      * (assuming the array's length is non-zero) represents the top of the
 688      * stack, which is the last method invocation in the sequence.  Typically,
 689      * this is the point at which this throwable was created and thrown.
 690      * The last element of the array (assuming the array's length is non-zero)
 691      * represents the bottom of the stack, which is the first method invocation
 692      * in the sequence.
 693      *
 694      * <p>Some virtual machines may, under some circumstances, omit one
 695      * or more stack frames from the stack trace.  In the extreme case,
 696      * a virtual machine that has no stack trace information concerning
 697      * this throwable is permitted to return a zero-length array from this
 698      * method.  Generally speaking, the array returned by this method will
 699      * contain one element for every frame that would be printed by
 700      * {@code printStackTrace}.
 701      *
 702      * @return an array of stack trace elements representing the stack trace
 703      *         pertaining to this throwable.
 704      * @since  1.4
 705      */
 706     public StackTraceElement[] getStackTrace() {
 707         return getOurStackTrace().clone();
 708     }
 709 
 710     private synchronized StackTraceElement[] getOurStackTrace() {
 711         // Initialize stack trace if this is the first call to this method
 712         if (stackTrace == null) {
 713             int depth = getStackTraceDepth();
 714             stackTrace = new StackTraceElement[depth];
 715             for (int i=0; i < depth; i++)
 716                 stackTrace[i] = getStackTraceElement(i);
 717         }
 718         return stackTrace;
 719     }
 720 
 721     /**
 722      * Sets the stack trace elements that will be returned by
 723      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
 724      * and related methods.
 725      *
 726      * This method, which is designed for use by RPC frameworks and other
 727      * advanced systems, allows the client to override the default
 728      * stack trace that is either generated by {@link #fillInStackTrace()}
 729      * when a throwable is constructed or deserialized when a throwable is
 730      * read from a serialization stream.
 731      *
 732      * @param   stackTrace the stack trace elements to be associated with
 733      * this {@code Throwable}.  The specified array is copied by this
 734      * call; changes in the specified array after the method invocation
 735      * returns will have no affect on this {@code Throwable}'s stack
 736      * trace.
 737      *
 738      * @throws NullPointerException if {@code stackTrace} is
 739      *         {@code null}, or if any of the elements of
 740      *         {@code stackTrace} are {@code null}
 741      *
 742      * @since  1.4
 743      */
 744     public void setStackTrace(StackTraceElement[] stackTrace) {
 745         StackTraceElement[] defensiveCopy = stackTrace.clone();
 746         for (int i = 0; i < defensiveCopy.length; i++)
 747             if (defensiveCopy[i] == null)
 748                 throw new NullPointerException("stackTrace[" + i + "]");
 749 
 750         this.stackTrace = defensiveCopy;
 751     }
 752 
 753     /**
 754      * Returns the number of elements in the stack trace (or 0 if the stack
 755      * trace is unavailable).
 756      *
 757      * package-protection for use by SharedSecrets.
 758      */
 759     native int getStackTraceDepth();
 760 
 761     /**
 762      * Returns the specified element of the stack trace.
 763      *
 764      * package-protection for use by SharedSecrets.
 765      *
 766      * @param index index of the element to return.
 767      * @throws IndexOutOfBoundsException if {@code index < 0 ||
 768      *         index >= getStackTraceDepth() }
 769      */
 770     native StackTraceElement getStackTraceElement(int index);
 771 
 772     private void readObject(ObjectInputStream s)
 773         throws IOException, ClassNotFoundException {
 774         s.defaultReadObject();     // read in all fields
 775         List<Throwable> suppressed = Collections.emptyList();
 776         if (suppressedExceptions != null &&
 777             !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
 778             suppressed = new ArrayList<Throwable>();
 779             for(Throwable t : suppressedExceptions) {
 780                 if (t == null)
 781                     throw new NullPointerException(NULL_CAUSE_MESSAGE);
 782                 suppressed.add(t);
 783             }
 784         }
 785         suppressedExceptions = suppressed;
 786     }
 787 
 788     private synchronized void writeObject(ObjectOutputStream s)
 789         throws IOException
 790     {
 791         getOurStackTrace();  // Ensure that stackTrace field is initialized.
 792         s.defaultWriteObject();
 793     }
 794 
 795     /**
 796      * Adds the specified exception to the list of exceptions that
 797      * were suppressed, typically by the automatic resource management
 798      * statement, in order to deliver this exception.
 799      *
 800      * <p>Note that when one exception {@linkplain
 801      * #initCause(Throwable) causes} another exception, the first
 802      * exception is usually caught and then the second exception is
 803      * thrown in response.  In contrast, when when one exception
 804      * suppresses another, two exceptions are thrown in sibling code
 805      * blocks, such as in a {@code try} block and in its {@code
 806      * finally} block, and control flow can only continue with one
 807      * exception so the second is recorded as a suppressed exception
 808      * of the first.
 809      *
 810      * @param exception the exception to be added to the list of
 811      *        suppressed exceptions
 812      * @throws NullPointerException if {@code exception} is null
 813      * @throws IllegalArgumentException if {@code exception} is this
 814      *         throwable; a throwable cannot suppress itself.
 815      * @since 1.7
 816      */
 817     public synchronized void addSuppressedException(Throwable exception) {
 818         if (exception == null)
 819             throw new NullPointerException(NULL_CAUSE_MESSAGE);
 820         if (exception == this)
 821             throw new IllegalArgumentException("Self-suppression not permitted");
 822 
 823         if (suppressedExceptions.size() == 0)
 824             suppressedExceptions = new ArrayList<Throwable>();
 825         suppressedExceptions.add(exception);
 826     }
 827 
 828     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 829 
 830     /**
 831      * Returns an array containing all of the exceptions that were
 832      * suppressed, typically by the automatic resource management
 833      * statement, in order to deliver this exception.
 834      *
 835      * @return an array containing all of the exceptions that were
 836      *         suppressed to deliver this exception.
 837      * @since 1.7
 838      */
 839     public Throwable[] getSuppressedExceptions() {
 840         return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 841     }