1 /*
   2  * Copyright (c) 1994, 2010, 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} 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 //     /**
 174 //      * Holder class to defer initializing sentinel objects only used
 175 //      * for serialization.
 176 //      */
 177 //     private static class SentinelHolder {
 178 //         /**
 179 //          * {@linkplain #setStackTrace(StackTraceElement[]) Setting the
 180 //          * stack trace} to a one-element array containing this sentinel
 181 //          * value indicates future attempts to set the stack trace will be
 182 //          * ignored.  The sentinal is equal to the result of calling:<br>
 183 //          * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
 184 //          */
 185 //         public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
 186 //             new StackTraceElement("", "", null, Integer.MIN_VALUE);
 187 
 188 //         /**
 189 //          * Sentinel value used in the serial form to indicate an immutable
 190 //          * stack trace.
 191 //          */
 192 //         public static final StackTraceElement[] STACK_TRACE_SENTINEL = 
 193 //             new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
 194 //     }
 195 
 196 //     /**
 197 //      * A value indicating the stack trace field has not yet been initialized.
 198 //      */
 199 //     private static final StackTraceElement[] UNINITIALIZED_STACK =
 200 //         new StackTraceElement[] {new StackTraceElement("UNINITIALIZED", "STACK", null, -1)};
 201 
 202 //     private static final StackTraceElement[] FILLED_IN_STACK =
 203 //         new StackTraceElement[] {new StackTraceElement("FILLED_IN", "STACK", null, -1)};
 204 
 205     /**
 206      * A shared value for an empty stack.
 207      */
 208     private static final StackTraceElement[] EMPTY_STACK = new StackTraceElement[0];
 209 
 210     /*
 211      * To allow Throwable objects to be made immutable and safely
 212      * reused by the JVM, such as OutOfMemoryErrors, fields of
 213      * Throwable that are writable in response to user actions, cause
 214      * and suppressedExceptions obey the following protocol:
 215      *
 216      * 1) The fields are initialized to a non-null sentinel value
 217      * which indicates the value has logically not been set.
 218      *
 219      * 2) Writing a null to the field indicates further writes
 220      * are forbidden
 221      * 
 222      * 3) The sentinel value may be replaced with another non-null
 223      * value.
 224      *
 225      * For example, implementations of the HotSpot JVM have
 226      * preallocated OutOfMemoryError objects to provide for better
 227      * diagnosability of that situation.  These objects are created
 228      * without calling the constructor for that class and the fields
 229      * in question are initialized to null.  To support this
 230      * capability, any new fields added to Throwable that require
 231      * being initialized to a non-null value require a coordinated JVM
 232      * change.
 233      */
 234 
 235     /**
 236      * The throwable that caused this throwable to get thrown, or null if this
 237      * throwable was not caused by another throwable, or if the causative
 238      * throwable is unknown.  If this field is equal to this throwable itself,
 239      * it indicates that the cause of this throwable has not yet been
 240      * initialized.
 241      *
 242      * @serial
 243      * @since 1.4
 244      */
 245     private Throwable cause = this;
 246 
 247     /**
 248      * The stack trace, as returned by {@link #getStackTrace()}.
 249      *
 250      * @serial
 251      * @since 1.4
 252      */
 253     private StackTraceElement[] stackTrace;
 254 
 255     // Setting this static field introduces an acceptable
 256     // initialization dependency on a few java.util classes.
 257     private static final List<Throwable> SUPPRESSED_SENTINEL =
 258         Collections.unmodifiableList(new ArrayList<Throwable>(0));
 259 
 260     /**
 261      * The list of suppressed exceptions, as returned by {@link
 262      * #getSuppressed()}.  The list is initialized to a zero-element
 263      * unmodifiable sentinel list.  When a serialized Throwable is
 264      * read in, if the {@code suppressedExceptions} field points to a
 265      * zero-element list, the field is reset to the sentinel value.
 266      *
 267      * @serial
 268      * @since 1.7
 269      */
 270     private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
 271 
 272     /** Message for trying to suppress a null exception. */
 273     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
 274 
 275     /** Message for trying to suppress oneself. */
 276     private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
 277 
 278     /** Caption  for labeling causative exception stack traces */
 279     private static final String CAUSE_CAPTION = "Caused by: ";
 280 
 281     /** Caption for labeling suppressed exception stack traces */
 282     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
 283 
 284     /**
 285      * Constructs a new throwable with {@code null} as its detail message.
 286      * The cause is not initialized, and may subsequently be initialized by a
 287      * call to {@link #initCause}.
 288      *
 289      * <p>The {@link #fillInStackTrace()} method is called to initialize
 290      * the stack trace data in the newly created throwable.
 291      */
 292     public Throwable() {
 293         fillInStackTrace();
 294     }
 295 
 296     /**
 297      * Constructs a new throwable with the specified detail message.  The
 298      * cause is not initialized, and may subsequently be initialized by
 299      * a call to {@link #initCause}.
 300      *
 301      * <p>The {@link #fillInStackTrace()} method is called to initialize
 302      * the stack trace data in the newly created throwable.
 303      *
 304      * @param   message   the detail message. The detail message is saved for
 305      *          later retrieval by the {@link #getMessage()} method.
 306      */
 307     public Throwable(String message) {
 308         fillInStackTrace();
 309         detailMessage = message;
 310     }
 311 
 312     /**
 313      * Constructs a new throwable with the specified detail message and
 314      * cause.  <p>Note that the detail message associated with
 315      * {@code cause} is <i>not</i> automatically incorporated in
 316      * this throwable's detail message.
 317      *
 318      * <p>The {@link #fillInStackTrace()} method is called to initialize
 319      * the stack trace data in the newly created throwable.
 320      *
 321      * @param  message the detail message (which is saved for later retrieval
 322      *         by the {@link #getMessage()} method).
 323      * @param  cause the cause (which is saved for later retrieval by the
 324      *         {@link #getCause()} method).  (A {@code null} value is
 325      *         permitted, and indicates that the cause is nonexistent or
 326      *         unknown.)
 327      * @since  1.4
 328      */
 329     public Throwable(String message, Throwable cause) {
 330         fillInStackTrace();
 331         detailMessage = message;
 332         this.cause = cause;
 333     }
 334 
 335     /**
 336      * Constructs a new throwable with the specified cause and a detail
 337      * message of {@code (cause==null ? null : cause.toString())} (which
 338      * typically contains the class and detail message of {@code cause}).
 339      * This constructor is useful for throwables that are little more than
 340      * wrappers for other throwables (for example, {@link
 341      * java.security.PrivilegedActionException}).
 342      *
 343      * <p>The {@link #fillInStackTrace()} method is called to initialize
 344      * the stack trace data in the newly created throwable.
 345      *
 346      * @param  cause the cause (which is saved for later retrieval by the
 347      *         {@link #getCause()} method).  (A {@code null} value is
 348      *         permitted, and indicates that the cause is nonexistent or
 349      *         unknown.)
 350      * @since  1.4
 351      */
 352     public Throwable(Throwable cause) {
 353         fillInStackTrace();
 354         detailMessage = (cause==null ? null : cause.toString());
 355         this.cause = cause;
 356     }
 357 
 358     /**
 359      * Returns the detail message string of this throwable.
 360      *
 361      * @return  the detail message string of this {@code Throwable} instance
 362      *          (which may be {@code null}).
 363      */
 364     public String getMessage() {
 365         return detailMessage;
 366     }
 367 
 368     /**
 369      * Creates a localized description of this throwable.
 370      * Subclasses may override this method in order to produce a
 371      * locale-specific message.  For subclasses that do not override this
 372      * method, the default implementation returns the same result as
 373      * {@code getMessage()}.
 374      *
 375      * @return  The localized description of this throwable.
 376      * @since   JDK1.1
 377      */
 378     public String getLocalizedMessage() {
 379         return getMessage();
 380     }
 381 
 382     /**
 383      * Returns the cause of this throwable or {@code null} if the
 384      * cause is nonexistent or unknown.  (The cause is the throwable that
 385      * caused this throwable to get thrown.)
 386      *
 387      * <p>This implementation returns the cause that was supplied via one of
 388      * the constructors requiring a {@code Throwable}, or that was set after
 389      * creation with the {@link #initCause(Throwable)} method.  While it is
 390      * typically unnecessary to override this method, a subclass can override
 391      * it to return a cause set by some other means.  This is appropriate for
 392      * a "legacy chained throwable" that predates the addition of chained
 393      * exceptions to {@code Throwable}.  Note that it is <i>not</i>
 394      * necessary to override any of the {@code PrintStackTrace} methods,
 395      * all of which invoke the {@code getCause} method to determine the
 396      * cause of a throwable.
 397      *
 398      * @return  the cause of this throwable or {@code null} if the
 399      *          cause is nonexistent or unknown.
 400      * @since 1.4
 401      */
 402     public synchronized Throwable getCause() {
 403         return (cause==this ? null : cause);
 404     }
 405 
 406     /**
 407      * Initializes the <i>cause</i> of this throwable to the specified value.
 408      * (The cause is the throwable that caused this throwable to get thrown.)
 409      *
 410      * <p>This method can be called at most once.  It is generally called from
 411      * within the constructor, or immediately after creating the
 412      * throwable.  If this throwable was created
 413      * with {@link #Throwable(Throwable)} or
 414      * {@link #Throwable(String,Throwable)}, this method cannot be called
 415      * even once.
 416      *
 417      * @param  cause the cause (which is saved for later retrieval by the
 418      *         {@link #getCause()} method).  (A {@code null} value is
 419      *         permitted, and indicates that the cause is nonexistent or
 420      *         unknown.)
 421      * @return  a reference to this {@code Throwable} instance.
 422      * @throws IllegalArgumentException if {@code cause} is this
 423      *         throwable.  (A throwable cannot be its own cause.)
 424      * @throws IllegalStateException if this throwable was
 425      *         created with {@link #Throwable(Throwable)} or
 426      *         {@link #Throwable(String,Throwable)}, or this method has already
 427      *         been called on this throwable.
 428      * @since  1.4
 429      */
 430     public synchronized Throwable initCause(Throwable cause) {
 431         if (this.cause != this)
 432             throw new IllegalStateException("Can't overwrite cause");
 433         if (cause == this)
 434             throw new IllegalArgumentException("Self-causation not permitted");
 435         this.cause = cause;
 436         return this;
 437     }
 438 
 439     /**
 440      * Returns a short description of this throwable.
 441      * The result is the concatenation of:
 442      * <ul>
 443      * <li> the {@linkplain Class#getName() name} of the class of this object
 444      * <li> ": " (a colon and a space)
 445      * <li> the result of invoking this object's {@link #getLocalizedMessage}
 446      *      method
 447      * </ul>
 448      * If {@code getLocalizedMessage} returns {@code null}, then just
 449      * the class name is returned.
 450      *
 451      * @return a string representation of this throwable.
 452      */
 453     public String toString() {
 454         String s = getClass().getName();
 455         String message = getLocalizedMessage();
 456         return (message != null) ? (s + ": " + message) : s;
 457     }
 458 
 459     /**
 460      * Prints this throwable and its backtrace to the
 461      * standard error stream. This method prints a stack trace for this
 462      * {@code Throwable} object on the error output stream that is
 463      * the value of the field {@code System.err}. The first line of
 464      * output contains the result of the {@link #toString()} method for
 465      * this object.  Remaining lines represent data previously recorded by
 466      * the method {@link #fillInStackTrace()}. The format of this
 467      * information depends on the implementation, but the following
 468      * example may be regarded as typical:
 469      * <blockquote><pre>
 470      * java.lang.NullPointerException
 471      *         at MyClass.mash(MyClass.java:9)
 472      *         at MyClass.crunch(MyClass.java:6)
 473      *         at MyClass.main(MyClass.java:3)
 474      * </pre></blockquote>
 475      * This example was produced by running the program:
 476      * <pre>
 477      * class MyClass {
 478      *     public static void main(String[] args) {
 479      *         crunch(null);
 480      *     }
 481      *     static void crunch(int[] a) {
 482      *         mash(a);
 483      *     }
 484      *     static void mash(int[] b) {
 485      *         System.out.println(b[0]);
 486      *     }
 487      * }
 488      * </pre>
 489      * The backtrace for a throwable with an initialized, non-null cause
 490      * should generally include the backtrace for the cause.  The format
 491      * of this information depends on the implementation, but the following
 492      * example may be regarded as typical:
 493      * <pre>
 494      * HighLevelException: MidLevelException: LowLevelException
 495      *         at Junk.a(Junk.java:13)
 496      *         at Junk.main(Junk.java:4)
 497      * Caused by: MidLevelException: LowLevelException
 498      *         at Junk.c(Junk.java:23)
 499      *         at Junk.b(Junk.java:17)
 500      *         at Junk.a(Junk.java:11)
 501      *         ... 1 more
 502      * Caused by: LowLevelException
 503      *         at Junk.e(Junk.java:30)
 504      *         at Junk.d(Junk.java:27)
 505      *         at Junk.c(Junk.java:21)
 506      *         ... 3 more
 507      * </pre>
 508      * Note the presence of lines containing the characters {@code "..."}.
 509      * These lines indicate that the remainder of the stack trace for this
 510      * exception matches the indicated number of frames from the bottom of the
 511      * stack trace of the exception that was caused by this exception (the
 512      * "enclosing" exception).  This shorthand can greatly reduce the length
 513      * of the output in the common case where a wrapped exception is thrown
 514      * from same method as the "causative exception" is caught.  The above
 515      * example was produced by running the program:
 516      * <pre>
 517      * public class Junk {
 518      *     public static void main(String args[]) {
 519      *         try {
 520      *             a();
 521      *         } catch(HighLevelException e) {
 522      *             e.printStackTrace();
 523      *         }
 524      *     }
 525      *     static void a() throws HighLevelException {
 526      *         try {
 527      *             b();
 528      *         } catch(MidLevelException e) {
 529      *             throw new HighLevelException(e);
 530      *         }
 531      *     }
 532      *     static void b() throws MidLevelException {
 533      *         c();
 534      *     }
 535      *     static void c() throws MidLevelException {
 536      *         try {
 537      *             d();
 538      *         } catch(LowLevelException e) {
 539      *             throw new MidLevelException(e);
 540      *         }
 541      *     }
 542      *     static void d() throws LowLevelException {
 543      *        e();
 544      *     }
 545      *     static void e() throws LowLevelException {
 546      *         throw new LowLevelException();
 547      *     }
 548      * }
 549      *
 550      * class HighLevelException extends Exception {
 551      *     HighLevelException(Throwable cause) { super(cause); }
 552      * }
 553      *
 554      * class MidLevelException extends Exception {
 555      *     MidLevelException(Throwable cause)  { super(cause); }
 556      * }
 557      *
 558      * class LowLevelException extends Exception {
 559      * }
 560      * </pre>
 561      * As of release 7, the platform supports the notion of
 562      * <i>suppressed exceptions</i> (in conjunction with the {@code
 563      * try}-with-resources statement). Any exceptions that were
 564      * suppressed in order to deliver an exception are printed out
 565      * beneath the stack trace.  The format of this information
 566      * depends on the implementation, but the following example may be
 567      * regarded as typical:
 568      *
 569      * <pre>
 570      * Exception in thread "main" java.lang.Exception: Something happened
 571      *  at Foo.bar(Foo.java:10)
 572      *  at Foo.main(Foo.java:5)
 573      *  Suppressed: Resource$CloseFailException: Resource ID = 0
 574      *          at Resource.close(Resource.java:26)
 575      *          at Foo.bar(Foo.java:9)
 576      *          ... 1 more
 577      * </pre>
 578      * Note that the "... n more" notation is used on suppressed exceptions
 579      * just at it is used on causes. Unlike causes, suppressed exceptions are
 580      * indented beyond their "containing exceptions."
 581      *
 582      * <p>An exception can have both a cause and one or more suppressed
 583      * exceptions:
 584      * <pre>
 585      * Exception in thread "main" java.lang.Exception: Main block
 586      *  at Foo3.main(Foo3.java:7)
 587      *  Suppressed: Resource$CloseFailException: Resource ID = 2
 588      *          at Resource.close(Resource.java:26)
 589      *          at Foo3.main(Foo3.java:5)
 590      *  Suppressed: Resource$CloseFailException: Resource ID = 1
 591      *          at Resource.close(Resource.java:26)
 592      *          at Foo3.main(Foo3.java:5)
 593      * Caused by: java.lang.Exception: I did it
 594      *  at Foo3.main(Foo3.java:8)
 595      * </pre>
 596      * Likewise, a suppressed exception can have a cause:
 597      * <pre>
 598      * Exception in thread "main" java.lang.Exception: Main block
 599      *  at Foo4.main(Foo4.java:6)
 600      *  Suppressed: Resource2$CloseFailException: Resource ID = 1
 601      *          at Resource2.close(Resource2.java:20)
 602      *          at Foo4.main(Foo4.java:5)
 603      *  Caused by: java.lang.Exception: Rats, you caught me
 604      *          at Resource2$CloseFailException.<init>(Resource2.java:45)
 605      *          ... 2 more
 606      * </pre>
 607      */
 608     public void printStackTrace() {
 609         printStackTrace(System.err);
 610     }
 611 
 612     /**
 613      * Prints this throwable and its backtrace to the specified print stream.
 614      *
 615      * @param s {@code PrintStream} to use for output
 616      */
 617     public void printStackTrace(PrintStream s) {
 618         printStackTrace(new WrappedPrintStream(s));
 619     }
 620 
 621     private void printStackTrace(PrintStreamOrWriter s) {
 622         // Guard against malicious overrides of Throwable.equals by
 623         // using a Set with identity equality semantics.
 624         Set<Throwable> dejaVu =
 625             Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
 626         dejaVu.add(this);
 627 
 628         synchronized (s.lock()) {
 629             // Print our stack trace
 630             s.println(this);
 631             StackTraceElement[] trace = getOurStackTrace();
 632             for (StackTraceElement traceElement : trace)
 633                 s.println("\tat " + traceElement);
 634 
 635             // Print suppressed exceptions, if any
 636             for (Throwable se : getSuppressed())
 637                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
 638 
 639             // Print cause, if any
 640             Throwable ourCause = getCause();
 641             if (ourCause != null)
 642                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
 643         }
 644     }
 645 
 646     /**
 647      * Print our stack trace as an enclosed exception for the specified
 648      * stack trace.
 649      */
 650     private void printEnclosedStackTrace(PrintStreamOrWriter s,
 651                                          StackTraceElement[] enclosingTrace,
 652                                          String caption,
 653                                          String prefix,
 654                                          Set<Throwable> dejaVu) {
 655         assert Thread.holdsLock(s.lock());
 656         if (dejaVu.contains(this)) {
 657             s.println("\t[CIRCULAR REFERENCE:" + this + "]");
 658         } else {
 659             dejaVu.add(this);
 660             // Compute number of frames in common between this and enclosing trace
 661             StackTraceElement[] trace = getOurStackTrace();
 662             int m = trace.length - 1;
 663             int n = enclosingTrace.length - 1;
 664             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
 665                 m--; n--;
 666             }
 667             int framesInCommon = trace.length - 1 - m;
 668 
 669             // Print our stack trace
 670             s.println(prefix + caption + this);
 671             for (int i = 0; i <= m; i++)
 672                 s.println(prefix + "\tat " + trace[i]);
 673             if (framesInCommon != 0)
 674                 s.println(prefix + "\t... " + framesInCommon + " more");
 675 
 676             // Print suppressed exceptions, if any
 677             for (Throwable se : getSuppressed())
 678                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
 679                                            prefix +"\t", dejaVu);
 680 
 681             // Print cause, if any
 682             Throwable ourCause = getCause();
 683             if (ourCause != null)
 684                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
 685         }
 686     }
 687 
 688     /**
 689      * Prints this throwable and its backtrace to the specified
 690      * print writer.
 691      *
 692      * @param s {@code PrintWriter} to use for output
 693      * @since   JDK1.1
 694      */
 695     public void printStackTrace(PrintWriter s) {
 696         printStackTrace(new WrappedPrintWriter(s));
 697     }
 698 
 699     /**
 700      * Wrapper class for PrintStream and PrintWriter to enable a single
 701      * implementation of printStackTrace.
 702      */
 703     private abstract static class PrintStreamOrWriter {
 704         /** Returns the object to be locked when using this StreamOrWriter */
 705         abstract Object lock();
 706 
 707         /** Prints the specified string as a line on this StreamOrWriter */
 708         abstract void println(Object o);
 709     }
 710 
 711     private static class WrappedPrintStream extends PrintStreamOrWriter {
 712         private final PrintStream printStream;
 713 
 714         WrappedPrintStream(PrintStream printStream) {
 715             this.printStream = printStream;
 716         }
 717 
 718         Object lock() {
 719             return printStream;
 720         }
 721 
 722         void println(Object o) {
 723             printStream.println(o);
 724         }
 725     }
 726 
 727     private static class WrappedPrintWriter extends PrintStreamOrWriter {
 728         private final PrintWriter printWriter;
 729 
 730         WrappedPrintWriter(PrintWriter printWriter) {
 731             this.printWriter = printWriter;
 732         }
 733 
 734         Object lock() {
 735             return printWriter;
 736         }
 737 
 738         void println(Object o) {
 739             printWriter.println(o);
 740         }
 741     }
 742 
 743     /**
 744      * Fills in the execution stack trace. This method records within this
 745      * {@code Throwable} object information about the current state of
 746      * the stack frames for the current thread.
 747      *
 748      * <p>If the stack trace of this {@code Throwable} {@linkplain
 749      * Throwable#setStackTrace(StackTraceElement[]) has been set} to
 750      * {@code null}, calling this method has no effect.
 751      *
 752      * @return  a reference to this {@code Throwable} instance.
 753      * @see     java.lang.Throwable#printStackTrace()
 754      */
 755     public native synchronized Throwable fillInStackTrace();
 756 
 757     /**
 758      * Provides programmatic access to the stack trace information printed by
 759      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
 760      * each representing one stack frame.  The zeroth element of the array
 761      * (assuming the array's length is non-zero) represents the top of the
 762      * stack, which is the last method invocation in the sequence.  Typically,
 763      * this is the point at which this throwable was created and thrown.
 764      * The last element of the array (assuming the array's length is non-zero)
 765      * represents the bottom of the stack, which is the first method invocation
 766      * in the sequence.
 767      *
 768      * <p>Some virtual machines may, under some circumstances, omit one
 769      * or more stack frames from the stack trace.  In the extreme case,
 770      * a virtual machine that has no stack trace information concerning
 771      * this throwable is permitted to return a zero-length array from this
 772      * method.  Generally speaking, the array returned by this method will
 773      * contain one element for every frame that would be printed by
 774      * {@code printStackTrace}.
 775      *
 776      * @return an array of stack trace elements representing the stack trace
 777      *         pertaining to this throwable.
 778      * @since  1.4
 779      */
 780     public StackTraceElement[] getStackTrace() {
 781         return getOurStackTrace().clone();
 782     }
 783 
 784     private synchronized StackTraceElement[] getOurStackTrace() {
 785         // Initialize stack trace if this is the first call to this method
 786         if (stackTrace == null) {
 787             int depth = getStackTraceDepth();
 788             stackTrace = new StackTraceElement[depth];
 789             for (int i=0; i < depth; i++)
 790                 stackTrace[i] = getStackTraceElement(i);
 791         }
 792         return stackTrace;
 793     }
 794 
 795     /**
 796      * Sets the stack trace elements that will be returned by
 797      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
 798      * and related methods.
 799      *
 800      * This method, which is designed for use by RPC frameworks and other
 801      * advanced systems, allows the client to override the default
 802      * stack trace that is either generated by {@link #fillInStackTrace()}
 803      * when a throwable is constructed or deserialized when a throwable is
 804      * read from a serialization stream.
 805      *
 806      * @param   stackTrace the stack trace elements to be associated with
 807      * this {@code Throwable}.  The specified array is copied by this
 808      * call; changes in the specified array after the method invocation
 809      * returns will have no affect on this {@code Throwable}'s stack
 810      * trace.
 811      *
 812      * @throws NullPointerException if any of the elements of
 813      *         {@code stackTrace} are {@code null}
 814      *
 815      * @since  1.4
 816      */
 817     public void setStackTrace(StackTraceElement[] stackTrace) {
 818         StackTraceElement[] defensiveCopy = stackTrace.clone();
 819         for (int i = 0; i < defensiveCopy.length; i++)
 820             if (defensiveCopy[i] == null)
 821                 throw new NullPointerException("stackTrace[" + i + "]");
 822         
 823         synchronized (this) {
 824             this.stackTrace = defensiveCopy;
 825         }
 826     }
 827 
 828     /**
 829      * Returns the number of elements in the stack trace (or 0 if the stack
 830      * trace is unavailable).
 831      *
 832      * package-protection for use by SharedSecrets.
 833      */
 834     native int getStackTraceDepth();
 835 
 836     /**
 837      * Returns the specified element of the stack trace.
 838      *
 839      * package-protection for use by SharedSecrets.
 840      *
 841      * @param index index of the element to return.
 842      * @throws IndexOutOfBoundsException if {@code index < 0 ||
 843      *         index >= getStackTraceDepth() }
 844      */
 845     native StackTraceElement getStackTraceElement(int index);
 846 
 847     /**
 848      * Read a {@code Throwable} from a stream, enforcing
 849      * well-formedness constraints on fields.  Null entries and
 850      * self-pointers are not allowed in the list of {@code
 851      * suppressedExceptions}.  Null entries are not allowed for stack
 852      * trace elements.
 853      *
 854      * Note that there are no constraints on the value the {@code
 855      * cause} field can hold; both {@code null} and this are valid
 856      * values for the field.
 857      */
 858     private void readObject(ObjectInputStream s)
 859         throws IOException, ClassNotFoundException {
 860         s.defaultReadObject();     // read in all fields
 861         if (suppressedExceptions != null) {
 862             List<Throwable> suppressed = null;
 863             if(suppressedExceptions.isEmpty()) {
 864                 // Use the sentinel for a zero-length list
 865                 suppressed = SUPPRESSED_SENTINEL;
 866             } else { // Copy Throwables to new list
 867                 suppressed = new ArrayList<Throwable>(1);
 868                 for (Throwable t : suppressedExceptions) {
 869                     // Enforce constraints on suppressed exceptions in
 870                     // case of corrupt or malicious stream.
 871                     if (t == null)
 872                         throw new NullPointerException(NULL_CAUSE_MESSAGE);
 873                     if (t == this)
 874                         throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 875                     suppressed.add(t);
 876                 }
 877             } 
 878             suppressedExceptions = suppressed;
 879         } // else a null suppressedExceptions field remains null
 880 
 881         if (stackTrace != null) {
 882             for(StackTraceElement ste : stackTrace) {
 883                 if (ste == null)
 884                     throw new NullPointerException("null StackTraceElement in serial stream. ");
 885             }
 886         } else {
 887             // A null stackTrace field in the serial form can result from
 888             // an exception serialized without that field in older JDK releases.
 889             stackTrace = EMPTY_STACK;
 890         }
 891 
 892     }
 893 
 894     /**
 895      * Write a {@code Throwable} object to a stream.
 896      */
 897     private synchronized void writeObject(ObjectOutputStream s)
 898         throws IOException {
 899         getOurStackTrace();  // Ensure that stackTrace field is initialized.
 900         s.defaultWriteObject()
 901     }
 902 
 903     /**
 904      * Adds the specified exception to the list of exceptions that
 905      * were suppressed, typically by the {@code try}-with-resources
 906      * statement, in order to deliver this exception.
 907      *
 908      * If the first exception to be suppressed is {@code null}, that
 909      * indicates suppressed exception information will <em>not</em> be
 910      * recorded for this exception.  Subsequent calls to this method
 911      * will not record any suppressed exceptions.  Otherwise,
 912      * attempting to suppress {@code null} after an exception has
 913      * already been successfully suppressed results in a {@code
 914      * NullPointerException}.
 915      *
 916      * <p>Note that when one exception {@linkplain
 917      * #initCause(Throwable) causes} another exception, the first
 918      * exception is usually caught and then the second exception is
 919      * thrown in response.  In contrast, when one exception suppresses
 920      * another, two exceptions are thrown in sibling code blocks, such
 921      * as in a {@code try} block and in its {@code finally} block, and
 922      * control flow can only continue with one exception so the second
 923      * is recorded as a suppressed exception of the first.
 924      *
 925      * @param exception the exception to be added to the list of
 926      *        suppressed exceptions
 927      * @throws IllegalArgumentException if {@code exception} is this
 928      *         throwable; a throwable cannot suppress itself.
 929      * @throws NullPointerException if {@code exception} is null and
 930      *         an exception has already been suppressed by this exception
 931      * @since 1.7
 932      */
 933     public final synchronized void addSuppressed(Throwable exception) {
 934         if (exception == this)
 935             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 936 
 937         if (exception == null) {
 938             if (suppressedExceptions == SUPPRESSED_SENTINEL) {
 939                 suppressedExceptions = null; // No suppression information recorded
 940                 return;
 941             } else
 942                 throw new NullPointerException(NULL_CAUSE_MESSAGE);
 943         } else {
 944             assert exception != null && exception != this;
 945 
 946             if (suppressedExceptions == null) // Suppressed exceptions not recorded
 947                 return;
 948 
 949             if (suppressedExceptions == SUPPRESSED_SENTINEL)
 950                 suppressedExceptions = new ArrayList<Throwable>(1);
 951 
 952             assert suppressedExceptions != SUPPRESSED_SENTINEL;
 953 
 954             suppressedExceptions.add(exception);
 955         }
 956     }
 957 
 958     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 959 
 960     /**
 961      * Returns an array containing all of the exceptions that were
 962      * suppressed, typically by the {@code try}-with-resources
 963      * statement, in order to deliver this exception.
 964      *
 965      * If no exceptions were suppressed, an empty array is returned.
 966      *
 967      * @return an array containing all of the exceptions that were
 968      *         suppressed to deliver this exception.
 969      * @since 1.7
 970      */
 971     public final synchronized Throwable[] getSuppressed() {
 972         if (suppressedExceptions == SUPPRESSED_SENTINEL ||
 973             suppressedExceptions == null)
 974             return EMPTY_THROWABLE_ARRAY;
 975         else
 976             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 977     }
 978 }