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