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