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