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