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