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