1 /*
   2  * Copyright (c) 1994, 2016, 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 
  28 import  java.io.*;
  29 import  java.util.*;
  30 
  31 /**
  32  * The {@code Throwable} class is the superclass of all errors and
  33  * exceptions in the Java language. Only objects that are instances of this
  34  * class (or one of its subclasses) are thrown by the Java Virtual Machine or
  35  * can be thrown by the Java {@code throw} statement. Similarly, only
  36  * this class or one of its subclasses can be the argument type in a
  37  * {@code catch} clause.
  38  *
  39  * For the purposes of compile-time checking of exceptions, {@code
  40  * Throwable} and any subclass of {@code Throwable} that is not also a
  41  * subclass of either {@link RuntimeException} or {@link Error} are
  42  * regarded as checked exceptions.
  43  *
  44  * <p>Instances of two subclasses, {@link java.lang.Error} and
  45  * {@link java.lang.Exception}, are conventionally used to indicate
  46  * that exceptional situations have occurred. Typically, these instances
  47  * are freshly created in the context of the exceptional situation so
  48  * as to include relevant information (such as stack trace data).
  49  *
  50  * <p>A throwable contains a snapshot of the execution stack of its
  51  * thread at the time it was created. It can also contain a message
  52  * string that gives more information about the error. Over time, a
  53  * throwable can {@linkplain Throwable#addSuppressed suppress} other
  54  * throwables from being propagated.  Finally, the throwable can also
  55  * contain a <i>cause</i>: another throwable that caused this
  56  * throwable to be constructed.  The recording of this causal information
  57  * is referred to as the <i>chained exception</i> facility, as the
  58  * cause can, itself, have a cause, and so on, leading to a "chain" of
  59  * exceptions, each caused by another.
  60  *
  61  * <p>One reason that a throwable may have a cause is that the class that
  62  * throws it is built atop a lower layered abstraction, and an operation on
  63  * the upper layer fails due to a failure in the lower layer.  It would be bad
  64  * design to let the throwable thrown by the lower layer propagate outward, as
  65  * it is generally unrelated to the abstraction provided by the upper layer.
  66  * Further, doing so would tie the API of the upper layer to the details of
  67  * its implementation, assuming the lower layer's exception was a checked
  68  * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
  69  * cause) allows the upper layer to communicate the details of the failure to
  70  * its caller without incurring either of these shortcomings.  It preserves
  71  * the flexibility to change the implementation of the upper layer without
  72  * changing its API (in particular, the set of exceptions thrown by its
  73  * methods).
  74  *
  75  * <p>A second reason that a throwable may have a cause is that the method
  76  * that throws it must conform to a general-purpose interface that does not
  77  * permit the method to throw the cause directly.  For example, suppose
  78  * a persistent collection conforms to the {@link java.util.Collection
  79  * Collection} interface, and that its persistence is implemented atop
  80  * {@code java.io}.  Suppose the internals of the {@code add} method
  81  * can throw an {@link java.io.IOException IOException}.  The implementation
  82  * can communicate the details of the {@code IOException} to its caller
  83  * while conforming to the {@code Collection} interface by wrapping the
  84  * {@code IOException} in an appropriate unchecked exception.  (The
  85  * specification for the persistent collection should indicate that it is
  86  * capable of throwing such exceptions.)
  87  *
  88  * <p>A cause can be associated with a throwable in two ways: via a
  89  * constructor that takes the cause as an argument, or via the
  90  * {@link #initCause(Throwable)} method.  New throwable classes that
  91  * wish to allow causes to be associated with them should provide constructors
  92  * that take a cause and delegate (perhaps indirectly) to one of the
  93  * {@code Throwable} constructors that takes a cause.
  94  *
  95  * Because the {@code initCause} method is public, it allows a cause to be
  96  * associated with any throwable, even a "legacy throwable" whose
  97  * implementation predates the addition of the exception chaining mechanism to
  98  * {@code Throwable}.
  99  *
 100  * <p>By convention, class {@code Throwable} and its subclasses have two
 101  * constructors, one that takes no arguments and one that takes a
 102  * {@code String} argument that can be used to produce a detail message.
 103  * Further, those subclasses that might likely have a cause associated with
 104  * them should have two more constructors, one that takes a
 105  * {@code Throwable} (the cause), and one that takes a
 106  * {@code String} (the detail message) and a {@code Throwable} (the
 107  * cause).
 108  *
 109  * @author  unascribed
 110  * @author  Josh Bloch (Added exception chaining and programmatic access to
 111  *          stack trace in 1.4.)
 112  * @jls 11.2 Compile-Time Checking of Exceptions
 113  * @since 1.0
 114  */
 115 public class Throwable implements Serializable {
 116     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 117     private static final long serialVersionUID = -3042686055658047285L;
 118 
 119     /**
 120      * The JVM saves some indication of the stack backtrace in this slot.
 121      */
 122     private transient Object backtrace;
 123 
 124     /**
 125      * Specific details about the Throwable.  For example, for
 126      * {@code FileNotFoundException}, this contains the name of
 127      * the file that could not be found.
 128      *
 129      * @serial
 130      */
 131     private String detailMessage;
 132 
 133 
 134     /**
 135      * Holder class to defer initializing sentinel objects only used
 136      * for serialization.
 137      */
 138     private static class SentinelHolder {
 139         /**
 140          * {@linkplain #setStackTrace(StackTraceElement[]) Setting the
 141          * stack trace} to a one-element array containing this sentinel
 142          * value indicates future attempts to set the stack trace will be
 143          * ignored.  The sentinel is equal to the result of calling:<br>
 144          * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
 145          */
 146         public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
 147             new StackTraceElement("", "", null, Integer.MIN_VALUE);
 148 
 149         /**
 150          * Sentinel value used in the serial form to indicate an immutable
 151          * stack trace.
 152          */
 153         public static final StackTraceElement[] STACK_TRACE_SENTINEL =
 154             new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
 155     }
 156 
 157     /**
 158      * A shared value for an empty stack.
 159      */
 160     private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];
 161 
 162     /*
 163      * To allow Throwable objects to be made immutable and safely
 164      * reused by the JVM, such as OutOfMemoryErrors, fields of
 165      * Throwable that are writable in response to user actions, cause,
 166      * stackTrace, and suppressedExceptions obey the following
 167      * protocol:
 168      *
 169      * 1) The fields are initialized to a non-null sentinel value
 170      * which indicates the value has logically not been set.
 171      *
 172      * 2) Writing a null to the field indicates further writes
 173      * are forbidden
 174      *
 175      * 3) The sentinel value may be replaced with another non-null
 176      * value.
 177      *
 178      * For example, implementations of the HotSpot JVM have
 179      * preallocated OutOfMemoryError objects to provide for better
 180      * diagnosability of that situation.  These objects are created
 181      * without calling the constructor for that class and the fields
 182      * in question are initialized to null.  To support this
 183      * capability, any new fields added to Throwable that require
 184      * being initialized to a non-null value require a coordinated JVM
 185      * change.
 186      */
 187 
 188     /**
 189      * The throwable that caused this throwable to get thrown, or null if this
 190      * throwable was not caused by another throwable, or if the causative
 191      * throwable is unknown.  If this field is equal to this throwable itself,
 192      * it indicates that the cause of this throwable has not yet been
 193      * initialized.
 194      *
 195      * @serial
 196      * @since 1.4
 197      */
 198     private Throwable cause = this;
 199 
 200     /**
 201      * The stack trace, as returned by {@link #getStackTrace()}.
 202      *
 203      * The field is initialized to a zero-length array.  A {@code
 204      * null} value of this field indicates subsequent calls to {@link
 205      * #setStackTrace(StackTraceElement[])} and {@link
 206      * #fillInStackTrace()} will be no-ops.
 207      *
 208      * @serial
 209      * @since 1.4
 210      */
 211     private StackTraceElement[] stackTrace = UNASSIGNED_STACK;
 212 
 213     /**
 214      * The JVM code sets the depth of the backtrace for later retrieval
 215      */
 216     private transient int depth;
 217 
 218     // Setting this static field introduces an acceptable
 219     // initialization dependency on a few java.util classes.
 220     private static final List<Throwable> SUPPRESSED_SENTINEL = Collections.emptyList();
 221 
 222     /**
 223      * The list of suppressed exceptions, as returned by {@link
 224      * #getSuppressed()}.  The list is initialized to a zero-element
 225      * unmodifiable sentinel list.  When a serialized Throwable is
 226      * read in, if the {@code suppressedExceptions} field points to a
 227      * zero-element list, the field is reset to the sentinel value.
 228      *
 229      * @serial
 230      * @since 1.7
 231      */
 232     private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
 233 
 234     /** Message for trying to suppress a null exception. */
 235     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
 236 
 237     /** Message for trying to suppress oneself. */
 238     private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
 239 
 240     /** Caption  for labeling causative exception stack traces */
 241     private static final String CAUSE_CAPTION = "Caused by: ";
 242 
 243     /** Caption for labeling suppressed exception stack traces */
 244     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
 245 
 246     /**
 247      * Constructs a new throwable with {@code null} as its detail message.
 248      * The cause is not initialized, and may subsequently be initialized by a
 249      * call to {@link #initCause}.
 250      *
 251      * <p>The {@link #fillInStackTrace()} method is called to initialize
 252      * the stack trace data in the newly created throwable.
 253      */
 254     public Throwable() {
 255         fillInStackTrace();
 256     }
 257 
 258     /**
 259      * Constructs a new throwable with the specified detail message.  The
 260      * cause is not initialized, and may subsequently be initialized by
 261      * a call to {@link #initCause}.
 262      *
 263      * <p>The {@link #fillInStackTrace()} method is called to initialize
 264      * the stack trace data in the newly created throwable.
 265      *
 266      * @param   message   the detail message. The detail message is saved for
 267      *          later retrieval by the {@link #getMessage()} method.
 268      */
 269     public Throwable(String message) {
 270         fillInStackTrace();
 271         detailMessage = message;
 272     }
 273 
 274     /**
 275      * Constructs a new throwable with the specified detail message and
 276      * cause.  <p>Note that the detail message associated with
 277      * {@code cause} is <i>not</i> automatically incorporated in
 278      * this throwable's detail message.
 279      *
 280      * <p>The {@link #fillInStackTrace()} method is called to initialize
 281      * the stack trace data in the newly created throwable.
 282      *
 283      * @param  message the detail message (which is saved for later retrieval
 284      *         by the {@link #getMessage()} method).
 285      * @param  cause the cause (which is saved for later retrieval by the
 286      *         {@link #getCause()} method).  (A {@code null} value is
 287      *         permitted, and indicates that the cause is nonexistent or
 288      *         unknown.)
 289      * @since  1.4
 290      */
 291     public Throwable(String message, Throwable cause) {
 292         fillInStackTrace();
 293         detailMessage = message;
 294         this.cause = cause;
 295     }
 296 
 297     /**
 298      * Constructs a new throwable with the specified cause and a detail
 299      * message of {@code (cause==null ? null : cause.toString())} (which
 300      * typically contains the class and detail message of {@code cause}).
 301      * This constructor is useful for throwables that are little more than
 302      * wrappers for other throwables (for example, {@link
 303      * java.security.PrivilegedActionException}).
 304      *
 305      * <p>The {@link #fillInStackTrace()} method is called to initialize
 306      * the stack trace data in the newly created throwable.
 307      *
 308      * @param  cause the cause (which is saved for later retrieval by the
 309      *         {@link #getCause()} method).  (A {@code null} value is
 310      *         permitted, and indicates that the cause is nonexistent or
 311      *         unknown.)
 312      * @since  1.4
 313      */
 314     public Throwable(Throwable cause) {
 315         fillInStackTrace();
 316         detailMessage = (cause==null ? null : cause.toString());
 317         this.cause = cause;
 318     }
 319 
 320     /**
 321      * Constructs a new throwable with the specified detail message,
 322      * cause, {@linkplain #addSuppressed suppression} enabled or
 323      * disabled, and writable stack trace enabled or disabled.  If
 324      * suppression is disabled, {@link #getSuppressed} for this object
 325      * will return a zero-length array and calls to {@link
 326      * #addSuppressed} that would otherwise append an exception to the
 327      * suppressed list will have no effect.  If the writable stack
 328      * trace is false, this constructor will not call {@link
 329      * #fillInStackTrace()}, a {@code null} will be written to the
 330      * {@code stackTrace} field, and subsequent calls to {@code
 331      * fillInStackTrace} and {@link
 332      * #setStackTrace(StackTraceElement[])} will not set the stack
 333      * trace.  If the writable stack trace is false, {@link
 334      * #getStackTrace} will return a zero length array.
 335      *
 336      * <p>Note that the other constructors of {@code Throwable} treat
 337      * suppression as being enabled and the stack trace as being
 338      * writable.  Subclasses of {@code Throwable} should document any
 339      * conditions under which suppression is disabled and document
 340      * conditions under which the stack trace is not writable.
 341      * Disabling of suppression should only occur in exceptional
 342      * circumstances where special requirements exist, such as a
 343      * virtual machine reusing exception objects under low-memory
 344      * situations.  Circumstances where a given exception object is
 345      * repeatedly caught and rethrown, such as to implement control
 346      * flow between two sub-systems, is another situation where
 347      * immutable throwable objects would be appropriate.
 348      *
 349      * @param  message the detail message.
 350      * @param cause the cause.  (A {@code null} value is permitted,
 351      * and indicates that the cause is nonexistent or unknown.)
 352      * @param enableSuppression whether or not suppression is enabled or disabled
 353      * @param writableStackTrace whether or not the stack trace should be
 354      *                           writable
 355      *
 356      * @see OutOfMemoryError
 357      * @see NullPointerException
 358      * @see ArithmeticException
 359      * @since 1.7
 360      */
 361     protected Throwable(String message, Throwable cause,
 362                         boolean enableSuppression,
 363                         boolean writableStackTrace) {
 364         if (writableStackTrace) {
 365             fillInStackTrace();
 366         } else {
 367             stackTrace = null;
 368         }
 369         detailMessage = message;
 370         this.cause = cause;
 371         if (!enableSuppression)
 372             suppressedExceptions = null;
 373     }
 374 
 375     /**
 376      * Returns the detail message string of this throwable.
 377      *
 378      * @return  the detail message string of this {@code Throwable} instance
 379      *          (which may be {@code null}).
 380      */
 381     public String getMessage() {
 382         return detailMessage;
 383     }
 384 
 385     /**
 386      * Creates a localized description of this throwable.
 387      * Subclasses may override this method in order to produce a
 388      * locale-specific message.  For subclasses that do not override this
 389      * method, the default implementation returns the same result as
 390      * {@code getMessage()}.
 391      *
 392      * @return  The localized description of this throwable.
 393      * @since   1.1
 394      */
 395     public String getLocalizedMessage() {
 396         return getMessage();
 397     }
 398 
 399     /**
 400      * Returns the cause of this throwable or {@code null} if the
 401      * cause is nonexistent or unknown.  (The cause is the throwable that
 402      * caused this throwable to get thrown.)
 403      *
 404      * <p>This implementation returns the cause that was supplied via one of
 405      * the constructors requiring a {@code Throwable}, or that was set after
 406      * creation with the {@link #initCause(Throwable)} method.  While it is
 407      * typically unnecessary to override this method, a subclass can override
 408      * it to return a cause set by some other means.  This is appropriate for
 409      * a "legacy chained throwable" that predates the addition of chained
 410      * exceptions to {@code Throwable}.  Note that it is <i>not</i>
 411      * necessary to override any of the {@code PrintStackTrace} methods,
 412      * all of which invoke the {@code getCause} method to determine the
 413      * cause of a throwable.
 414      *
 415      * @return  the cause of this throwable or {@code null} if the
 416      *          cause is nonexistent or unknown.
 417      * @since 1.4
 418      */
 419     public synchronized Throwable getCause() {
 420         return (cause==this ? null : cause);
 421     }
 422 
 423     /**
 424      * Initializes the <i>cause</i> of this throwable to the specified value.
 425      * (The cause is the throwable that caused this throwable to get thrown.)
 426      *
 427      * <p>This method can be called at most once.  It is generally called from
 428      * within the constructor, or immediately after creating the
 429      * throwable.  If this throwable was created
 430      * with {@link #Throwable(Throwable)} or
 431      * {@link #Throwable(String,Throwable)}, this method cannot be called
 432      * even once.
 433      *
 434      * <p>An example of using this method on a legacy throwable type
 435      * without other support for setting the cause is:
 436      *
 437      * <pre>
 438      * try {
 439      *     lowLevelOp();
 440      * } catch (LowLevelException le) {
 441      *     throw (HighLevelException)
 442      *           new HighLevelException().initCause(le); // Legacy constructor
 443      * }
 444      * </pre>
 445      *
 446      * @param  cause the cause (which is saved for later retrieval by the
 447      *         {@link #getCause()} method).  (A {@code null} value is
 448      *         permitted, and indicates that the cause is nonexistent or
 449      *         unknown.)
 450      * @return  a reference to this {@code Throwable} instance.
 451      * @throws IllegalArgumentException if {@code cause} is this
 452      *         throwable.  (A throwable cannot be its own cause.)
 453      * @throws IllegalStateException if this throwable was
 454      *         created with {@link #Throwable(Throwable)} or
 455      *         {@link #Throwable(String,Throwable)}, or this method has already
 456      *         been called on this throwable.
 457      * @since  1.4
 458      */
 459     public synchronized Throwable initCause(Throwable cause) {
 460         if (this.cause != this)
 461             throw new IllegalStateException("Can't overwrite cause with " +
 462                                             Objects.toString(cause, "a null"), this);
 463         if (cause == this)
 464             throw new IllegalArgumentException("Self-causation not permitted", this);
 465         this.cause = cause;
 466         return this;
 467     }
 468 
 469     /**
 470      * Returns a short description of this throwable.
 471      * The result is the concatenation of:
 472      * <ul>
 473      * <li> the {@linkplain Class#getName() name} of the class of this object
 474      * <li> ": " (a colon and a space)
 475      * <li> the result of invoking this object's {@link #getLocalizedMessage}
 476      *      method
 477      * </ul>
 478      * If {@code getLocalizedMessage} returns {@code null}, then just
 479      * the class name is returned.
 480      *
 481      * @return a string representation of this throwable.
 482      */
 483     public String toString() {
 484         String s = getClass().getName();
 485         String message = getLocalizedMessage();
 486         return (message != null) ? (s + ": " + message) : s;
 487     }
 488 
 489     /**
 490      * Prints this throwable and its backtrace to the
 491      * standard error stream. This method prints a stack trace for this
 492      * {@code Throwable} object on the error output stream that is
 493      * the value of the field {@code System.err}. The first line of
 494      * output contains the result of the {@link #toString()} method for
 495      * this object.  Remaining lines represent data previously recorded by
 496      * the method {@link #fillInStackTrace()}. The format of this
 497      * information depends on the implementation, but the following
 498      * example may be regarded as typical:
 499      * <blockquote><pre>
 500      * java.lang.NullPointerException
 501      *         at MyClass.mash(MyClass.java:9)
 502      *         at MyClass.crunch(MyClass.java:6)
 503      *         at MyClass.main(MyClass.java:3)
 504      * </pre></blockquote>
 505      * This example was produced by running the program:
 506      * <pre>
 507      * class MyClass {
 508      *     public static void main(String[] args) {
 509      *         crunch(null);
 510      *     }
 511      *     static void crunch(int[] a) {
 512      *         mash(a);
 513      *     }
 514      *     static void mash(int[] b) {
 515      *         System.out.println(b[0]);
 516      *     }
 517      * }
 518      * </pre>
 519      * The backtrace for a throwable with an initialized, non-null cause
 520      * should generally include the backtrace for the cause.  The format
 521      * of this information depends on the implementation, but the following
 522      * example may be regarded as typical:
 523      * <pre>
 524      * HighLevelException: MidLevelException: LowLevelException
 525      *         at Junk.a(Junk.java:13)
 526      *         at Junk.main(Junk.java:4)
 527      * Caused by: MidLevelException: LowLevelException
 528      *         at Junk.c(Junk.java:23)
 529      *         at Junk.b(Junk.java:17)
 530      *         at Junk.a(Junk.java:11)
 531      *         ... 1 more
 532      * Caused by: LowLevelException
 533      *         at Junk.e(Junk.java:30)
 534      *         at Junk.d(Junk.java:27)
 535      *         at Junk.c(Junk.java:21)
 536      *         ... 3 more
 537      * </pre>
 538      * Note the presence of lines containing the characters {@code "..."}.
 539      * These lines indicate that the remainder of the stack trace for this
 540      * exception matches the indicated number of frames from the bottom of the
 541      * stack trace of the exception that was caused by this exception (the
 542      * "enclosing" exception).  This shorthand can greatly reduce the length
 543      * of the output in the common case where a wrapped exception is thrown
 544      * from same method as the "causative exception" is caught.  The above
 545      * example was produced by running the program:
 546      * <pre>
 547      * public class Junk {
 548      *     public static void main(String args[]) {
 549      *         try {
 550      *             a();
 551      *         } catch(HighLevelException e) {
 552      *             e.printStackTrace();
 553      *         }
 554      *     }
 555      *     static void a() throws HighLevelException {
 556      *         try {
 557      *             b();
 558      *         } catch(MidLevelException e) {
 559      *             throw new HighLevelException(e);
 560      *         }
 561      *     }
 562      *     static void b() throws MidLevelException {
 563      *         c();
 564      *     }
 565      *     static void c() throws MidLevelException {
 566      *         try {
 567      *             d();
 568      *         } catch(LowLevelException e) {
 569      *             throw new MidLevelException(e);
 570      *         }
 571      *     }
 572      *     static void d() throws LowLevelException {
 573      *        e();
 574      *     }
 575      *     static void e() throws LowLevelException {
 576      *         throw new LowLevelException();
 577      *     }
 578      * }
 579      *
 580      * class HighLevelException extends Exception {
 581      *     HighLevelException(Throwable cause) { super(cause); }
 582      * }
 583      *
 584      * class MidLevelException extends Exception {
 585      *     MidLevelException(Throwable cause)  { super(cause); }
 586      * }
 587      *
 588      * class LowLevelException extends Exception {
 589      * }
 590      * </pre>
 591      * As of release 7, the platform supports the notion of
 592      * <i>suppressed exceptions</i> (in conjunction with the {@code
 593      * try}-with-resources statement). Any exceptions that were
 594      * suppressed in order to deliver an exception are printed out
 595      * beneath the stack trace.  The format of this information
 596      * depends on the implementation, but the following example may be
 597      * regarded as typical:
 598      *
 599      * <pre>
 600      * Exception in thread "main" java.lang.Exception: Something happened
 601      *  at Foo.bar(Foo.java:10)
 602      *  at Foo.main(Foo.java:5)
 603      *  Suppressed: Resource$CloseFailException: Resource ID = 0
 604      *          at Resource.close(Resource.java:26)
 605      *          at Foo.bar(Foo.java:9)
 606      *          ... 1 more
 607      * </pre>
 608      * Note that the "... n more" notation is used on suppressed exceptions
 609      * just at it is used on causes. Unlike causes, suppressed exceptions are
 610      * indented beyond their "containing exceptions."
 611      *
 612      * <p>An exception can have both a cause and one or more suppressed
 613      * exceptions:
 614      * <pre>
 615      * Exception in thread "main" java.lang.Exception: Main block
 616      *  at Foo3.main(Foo3.java:7)
 617      *  Suppressed: Resource$CloseFailException: Resource ID = 2
 618      *          at Resource.close(Resource.java:26)
 619      *          at Foo3.main(Foo3.java:5)
 620      *  Suppressed: Resource$CloseFailException: Resource ID = 1
 621      *          at Resource.close(Resource.java:26)
 622      *          at Foo3.main(Foo3.java:5)
 623      * Caused by: java.lang.Exception: I did it
 624      *  at Foo3.main(Foo3.java:8)
 625      * </pre>
 626      * Likewise, a suppressed exception can have a cause:
 627      * <pre>
 628      * Exception in thread "main" java.lang.Exception: Main block
 629      *  at Foo4.main(Foo4.java:6)
 630      *  Suppressed: Resource2$CloseFailException: Resource ID = 1
 631      *          at Resource2.close(Resource2.java:20)
 632      *          at Foo4.main(Foo4.java:5)
 633      *  Caused by: java.lang.Exception: Rats, you caught me
 634      *          at Resource2$CloseFailException.&lt;init&gt;(Resource2.java:45)
 635      *          ... 2 more
 636      * </pre>
 637      */
 638     public void printStackTrace() {
 639         printStackTrace(System.err);
 640     }
 641 
 642     /**
 643      * Prints this throwable and its backtrace to the specified print stream.
 644      *
 645      * @param s {@code PrintStream} to use for output
 646      */
 647     public void printStackTrace(PrintStream s) {
 648         printStackTrace(new WrappedPrintStream(s));
 649     }
 650 
 651     private void printStackTrace(PrintStreamOrWriter s) {
 652         // Guard against malicious overrides of Throwable.equals by
 653         // using a Set with identity equality semantics.
 654         Set<Throwable> dejaVu = Collections.newSetFromMap(new IdentityHashMap<>());
 655         dejaVu.add(this);
 656 
 657         synchronized (s.lock()) {
 658             // Print our stack trace
 659             s.println(this);
 660             StackTraceElement[] trace = getOurStackTrace();
 661             for (StackTraceElement traceElement : trace)
 662                 s.println("\tat " + traceElement);
 663 
 664             // Print suppressed exceptions, if any
 665             for (Throwable se : getSuppressed())
 666                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
 667 
 668             // Print cause, if any
 669             Throwable ourCause = getCause();
 670             if (ourCause != null)
 671                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
 672         }
 673     }
 674 
 675     /**
 676      * Print our stack trace as an enclosed exception for the specified
 677      * stack trace.
 678      */
 679     private void printEnclosedStackTrace(PrintStreamOrWriter s,
 680                                          StackTraceElement[] enclosingTrace,
 681                                          String caption,
 682                                          String prefix,
 683                                          Set<Throwable> dejaVu) {
 684         assert Thread.holdsLock(s.lock());
 685         if (dejaVu.contains(this)) {
 686             s.println("\t[CIRCULAR REFERENCE:" + this + "]");
 687         } else {
 688             dejaVu.add(this);
 689             // Compute number of frames in common between this and enclosing trace
 690             StackTraceElement[] trace = getOurStackTrace();
 691             int m = trace.length - 1;
 692             int n = enclosingTrace.length - 1;
 693             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
 694                 m--; n--;
 695             }
 696             int framesInCommon = trace.length - 1 - m;
 697 
 698             // Print our stack trace
 699             s.println(prefix + caption + this);
 700             for (int i = 0; i <= m; i++)
 701                 s.println(prefix + "\tat " + trace[i]);
 702             if (framesInCommon != 0)
 703                 s.println(prefix + "\t... " + framesInCommon + " more");
 704 
 705             // Print suppressed exceptions, if any
 706             for (Throwable se : getSuppressed())
 707                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
 708                                            prefix +"\t", dejaVu);
 709 
 710             // Print cause, if any
 711             Throwable ourCause = getCause();
 712             if (ourCause != null)
 713                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
 714         }
 715     }
 716 
 717     /**
 718      * Prints this throwable and its backtrace to the specified
 719      * print writer.
 720      *
 721      * @param s {@code PrintWriter} to use for output
 722      * @since   1.1
 723      */
 724     public void printStackTrace(PrintWriter s) {
 725         printStackTrace(new WrappedPrintWriter(s));
 726     }
 727 
 728     /**
 729      * Wrapper class for PrintStream and PrintWriter to enable a single
 730      * implementation of printStackTrace.
 731      */
 732     private abstract static class PrintStreamOrWriter {
 733         /** Returns the object to be locked when using this StreamOrWriter */
 734         abstract Object lock();
 735 
 736         /** Prints the specified string as a line on this StreamOrWriter */
 737         abstract void println(Object o);
 738     }
 739 
 740     private static class WrappedPrintStream extends PrintStreamOrWriter {
 741         private final PrintStream printStream;
 742 
 743         WrappedPrintStream(PrintStream printStream) {
 744             this.printStream = printStream;
 745         }
 746 
 747         Object lock() {
 748             return printStream;
 749         }
 750 
 751         void println(Object o) {
 752             printStream.println(o);
 753         }
 754     }
 755 
 756     private static class WrappedPrintWriter extends PrintStreamOrWriter {
 757         private final PrintWriter printWriter;
 758 
 759         WrappedPrintWriter(PrintWriter printWriter) {
 760             this.printWriter = printWriter;
 761         }
 762 
 763         Object lock() {
 764             return printWriter;
 765         }
 766 
 767         void println(Object o) {
 768             printWriter.println(o);
 769         }
 770     }
 771 
 772     /**
 773      * Fills in the execution stack trace. This method records within this
 774      * {@code Throwable} object information about the current state of
 775      * the stack frames for the current thread.
 776      *
 777      * <p>If the stack trace of this {@code Throwable} {@linkplain
 778      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
 779      * writable}, calling this method has no effect.
 780      *
 781      * @return  a reference to this {@code Throwable} instance.
 782      * @see     java.lang.Throwable#printStackTrace()
 783      */
 784     public synchronized Throwable fillInStackTrace() {
 785         if (stackTrace != null ||
 786             backtrace != null /* Out of protocol state */ ) {
 787             fillInStackTrace(0);
 788             stackTrace = UNASSIGNED_STACK;
 789         }
 790         return this;
 791     }
 792 
 793     private native Throwable fillInStackTrace(int dummy);
 794 
 795     /**
 796      * Provides programmatic access to the stack trace information printed by
 797      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
 798      * each representing one stack frame.  The zeroth element of the array
 799      * (assuming the array's length is non-zero) represents the top of the
 800      * stack, which is the last method invocation in the sequence.  Typically,
 801      * this is the point at which this throwable was created and thrown.
 802      * The last element of the array (assuming the array's length is non-zero)
 803      * represents the bottom of the stack, which is the first method invocation
 804      * in the sequence.
 805      *
 806      * <p>Some virtual machines may, under some circumstances, omit one
 807      * or more stack frames from the stack trace.  In the extreme case,
 808      * a virtual machine that has no stack trace information concerning
 809      * this throwable is permitted to return a zero-length array from this
 810      * method.  Generally speaking, the array returned by this method will
 811      * contain one element for every frame that would be printed by
 812      * {@code printStackTrace}.  Writes to the returned array do not
 813      * affect future calls to this method.
 814      *
 815      * @return an array of stack trace elements representing the stack trace
 816      *         pertaining to this throwable.
 817      * @since  1.4
 818      */
 819     public StackTraceElement[] getStackTrace() {
 820         return getOurStackTrace().clone();
 821     }
 822 
 823     private synchronized StackTraceElement[] getOurStackTrace() {
 824         // Initialize stack trace field with information from
 825         // backtrace if this is the first call to this method
 826         if (stackTrace == UNASSIGNED_STACK ||
 827             (stackTrace == null && backtrace != null) /* Out of protocol state */) {
 828             stackTrace = StackTraceElement.of(this, depth);
 829         } else if (stackTrace == null) {
 830             return UNASSIGNED_STACK;
 831         }
 832         return stackTrace;
 833     }
 834 
 835     /**
 836      * This method is currently only called from the VM for instances of
 837      * ExceptionInInitializerError which are stored for later chaining into a
 838      * NoClassDefFoundError in order to prevent keeping classes from the native
 839      * backtrace alive.
 840      */
 841     private static void removeNativeBacktrace(Throwable throwable) {
 842         Throwable t = throwable;
 843         while ((t != null)) {
 844             // Triggers the generation of the stack trace elements.
 845             t.getOurStackTrace();
 846             if (t.suppressedExceptions != null) {
 847                 // If there are any suppressed exceptions,
 848                 // remove their native backtraces as well.
 849                 for (Throwable s : t.suppressedExceptions) {
 850                     removeNativeBacktrace(s);
 851                 }
 852             }
 853             // Now we don't need the native backtrace any more
 854             t.backtrace = null;
 855             t = t.getCause();
 856         }
 857     }
 858 
 859     /**
 860      * Sets the stack trace elements that will be returned by
 861      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
 862      * and related methods.
 863      *
 864      * This method, which is designed for use by RPC frameworks and other
 865      * advanced systems, allows the client to override the default
 866      * stack trace that is either generated by {@link #fillInStackTrace()}
 867      * when a throwable is constructed or deserialized when a throwable is
 868      * read from a serialization stream.
 869      *
 870      * <p>If the stack trace of this {@code Throwable} {@linkplain
 871      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
 872      * writable}, calling this method has no effect other than
 873      * validating its argument.
 874      *
 875      * @param   stackTrace the stack trace elements to be associated with
 876      * this {@code Throwable}.  The specified array is copied by this
 877      * call; changes in the specified array after the method invocation
 878      * returns will have no affect on this {@code Throwable}'s stack
 879      * trace.
 880      *
 881      * @throws NullPointerException if {@code stackTrace} is
 882      *         {@code null} or if any of the elements of
 883      *         {@code stackTrace} are {@code null}
 884      *
 885      * @since  1.4
 886      */
 887     public void setStackTrace(StackTraceElement[] stackTrace) {
 888         // Validate argument
 889         StackTraceElement[] defensiveCopy = stackTrace.clone();
 890         for (int i = 0; i < defensiveCopy.length; i++) {
 891             if (defensiveCopy[i] == null)
 892                 throw new NullPointerException("stackTrace[" + i + "]");
 893         }
 894 
 895         synchronized (this) {
 896             if (this.stackTrace == null && // Immutable stack
 897                 backtrace == null) // Test for out of protocol state
 898                 return;
 899             this.stackTrace = defensiveCopy;
 900         }
 901     }
 902 
 903     /**
 904      * Reads a {@code Throwable} from a stream, enforcing
 905      * well-formedness constraints on fields.  Null entries and
 906      * self-pointers are not allowed in the list of {@code
 907      * suppressedExceptions}.  Null entries are not allowed for stack
 908      * trace elements.  A null stack trace in the serial form results
 909      * in a zero-length stack element array. A single-element stack
 910      * trace whose entry is equal to {@code new StackTraceElement("",
 911      * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
 912      * stackTrace} field.
 913      *
 914      * Note that there are no constraints on the value the {@code
 915      * cause} field can hold; both {@code null} and {@code this} are
 916      * valid values for the field.
 917      */
 918     private void readObject(ObjectInputStream s)
 919         throws IOException, ClassNotFoundException {
 920         s.defaultReadObject();     // read in all fields
 921         if (suppressedExceptions != null) {
 922             List<Throwable> suppressed = null;
 923             if (suppressedExceptions.isEmpty()) {
 924                 // Use the sentinel for a zero-length list
 925                 suppressed = SUPPRESSED_SENTINEL;
 926             } else { // Copy Throwables to new list
 927                 suppressed = new ArrayList<>(1);
 928                 for (Throwable t : suppressedExceptions) {
 929                     // Enforce constraints on suppressed exceptions in
 930                     // case of corrupt or malicious stream.
 931                     if (t == null)
 932                         throw new NullPointerException(NULL_CAUSE_MESSAGE);
 933                     if (t == this)
 934                         throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 935                     suppressed.add(t);
 936                 }
 937             }
 938             suppressedExceptions = suppressed;
 939         } // else a null suppressedExceptions field remains null
 940 
 941         /*
 942          * For zero-length stack traces, use a clone of
 943          * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
 944          * allow identity comparison against UNASSIGNED_STACK in
 945          * getOurStackTrace.  The identity of UNASSIGNED_STACK in
 946          * stackTrace indicates to the getOurStackTrace method that
 947          * the stackTrace needs to be constructed from the information
 948          * in backtrace.
 949          */
 950         if (stackTrace != null) {
 951             if (stackTrace.length == 0) {
 952                 stackTrace = UNASSIGNED_STACK.clone();
 953             }  else if (stackTrace.length == 1 &&
 954                         // Check for the marker of an immutable stack trace
 955                         SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) {
 956                 stackTrace = null;
 957             } else { // Verify stack trace elements are non-null.
 958                 for(StackTraceElement ste : stackTrace) {
 959                     if (ste == null)
 960                         throw new NullPointerException("null StackTraceElement in serial stream. ");
 961                 }
 962             }
 963         } else {
 964             // A null stackTrace field in the serial form can result
 965             // from an exception serialized without that field in
 966             // older JDK releases; treat such exceptions as having
 967             // empty stack traces.
 968             stackTrace = UNASSIGNED_STACK.clone();
 969         }
 970     }
 971 
 972     /**
 973      * Write a {@code Throwable} object to a stream.
 974      *
 975      * A {@code null} stack trace field is represented in the serial
 976      * form as a one-element array whose element is equal to {@code
 977      * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
 978      */
 979     private synchronized void writeObject(ObjectOutputStream s)
 980         throws IOException {
 981         // Ensure that the stackTrace field is initialized to a
 982         // non-null value, if appropriate.  As of JDK 7, a null stack
 983         // trace field is a valid value indicating the stack trace
 984         // should not be set.
 985         getOurStackTrace();
 986 
 987         StackTraceElement[] oldStackTrace = stackTrace;
 988         try {
 989             if (stackTrace == null)
 990                 stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
 991             s.defaultWriteObject();
 992         } finally {
 993             stackTrace = oldStackTrace;
 994         }
 995     }
 996 
 997     /**
 998      * Appends the specified exception to the exceptions that were
 999      * suppressed in order to deliver this exception. This method is
1000      * thread-safe and typically called (automatically and implicitly)
1001      * by the {@code try}-with-resources statement.
1002      *
1003      * <p>The suppression behavior is enabled <em>unless</em> disabled
1004      * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
1005      * a constructor}.  When suppression is disabled, this method does
1006      * nothing other than to validate its argument.
1007      *
1008      * <p>Note that when one exception {@linkplain
1009      * #initCause(Throwable) causes} another exception, the first
1010      * exception is usually caught and then the second exception is
1011      * thrown in response.  In other words, there is a causal
1012      * connection between the two exceptions.
1013      *
1014      * In contrast, there are situations where two independent
1015      * exceptions can be thrown in sibling code blocks, in particular
1016      * in the {@code try} block of a {@code try}-with-resources
1017      * statement and the compiler-generated {@code finally} block
1018      * which closes the resource.
1019      *
1020      * In these situations, only one of the thrown exceptions can be
1021      * propagated.  In the {@code try}-with-resources statement, when
1022      * there are two such exceptions, the exception originating from
1023      * the {@code try} block is propagated and the exception from the
1024      * {@code finally} block is added to the list of exceptions
1025      * suppressed by the exception from the {@code try} block.  As an
1026      * exception unwinds the stack, it can accumulate multiple
1027      * suppressed exceptions.
1028      *
1029      * <p>An exception may have suppressed exceptions while also being
1030      * caused by another exception.  Whether or not an exception has a
1031      * cause is semantically known at the time of its creation, unlike
1032      * whether or not an exception will suppress other exceptions
1033      * which is typically only determined after an exception is
1034      * thrown.
1035      *
1036      * <p>Note that programmer written code is also able to take
1037      * advantage of calling this method in situations where there are
1038      * multiple sibling exceptions and only one can be propagated.
1039      *
1040      * @param exception the exception to be added to the list of
1041      *        suppressed exceptions
1042      * @throws IllegalArgumentException if {@code exception} is this
1043      *         throwable; a throwable cannot suppress itself.
1044      * @throws NullPointerException if {@code exception} is {@code null}
1045      * @since 1.7
1046      */
1047     public final synchronized void addSuppressed(Throwable exception) {
1048         if (exception == this)
1049             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception);
1050 
1051         if (exception == null)
1052             throw new NullPointerException(NULL_CAUSE_MESSAGE);
1053 
1054         if (suppressedExceptions == null) // Suppressed exceptions not recorded
1055             return;
1056 
1057         if (suppressedExceptions == SUPPRESSED_SENTINEL)
1058             suppressedExceptions = new ArrayList<>(1);
1059 
1060         suppressedExceptions.add(exception);
1061     }
1062 
1063     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
1064 
1065     /**
1066      * Returns an array containing all of the exceptions that were
1067      * suppressed, typically by the {@code try}-with-resources
1068      * statement, in order to deliver this exception.
1069      *
1070      * If no exceptions were suppressed or {@linkplain
1071      * #Throwable(String, Throwable, boolean, boolean) suppression is
1072      * disabled}, an empty array is returned.  This method is
1073      * thread-safe.  Writes to the returned array do not affect future
1074      * calls to this method.
1075      *
1076      * @return an array containing all of the exceptions that were
1077      *         suppressed to deliver this exception.
1078      * @since 1.7
1079      */
1080     public final synchronized Throwable[] getSuppressed() {
1081         if (suppressedExceptions == SUPPRESSED_SENTINEL ||
1082             suppressedExceptions == null)
1083             return EMPTY_THROWABLE_ARRAY;
1084         else
1085             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
1086     }
1087 }