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