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