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