1 /*
   2  * Copyright (c) 1994, 2010, 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 thread at
  50  * the time it was created. It can also contain a message string that gives
  51  * more information about the error. Finally, it can contain a <i>cause</i>:
  52  * another throwable that caused this throwable to get thrown.  The cause
  53  * facility is new in release 1.4.  It is also known as the <i>chained
  54  * exception</i> facility, as the cause can, itself, have a cause, and so on,
  55  * leading to a "chain" of exceptions, each caused by another.
  56  *
  57  * <p>One reason that a throwable may have a cause is that the class that
  58  * throws it is built atop a lower layered abstraction, and an operation on
  59  * the upper layer fails due to a failure in the lower layer.  It would be bad
  60  * design to let the throwable thrown by the lower layer propagate outward, as
  61  * it is generally unrelated to the abstraction provided by the upper layer.
  62  * Further, doing so would tie the API of the upper layer to the details of
  63  * its implementation, assuming the lower layer's exception was a checked
  64  * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
  65  * cause) allows the upper layer to communicate the details of the failure to
  66  * its caller without incurring either of these shortcomings.  It preserves
  67  * the flexibility to change the implementation of the upper layer without
  68  * changing its API (in particular, the set of exceptions thrown by its
  69  * methods).
  70  *
  71  * <p>A second reason that a throwable may have a cause is that the method
  72  * that throws it must conform to a general-purpose interface that does not
  73  * permit the method to throw the cause directly.  For example, suppose
  74  * a persistent collection conforms to the {@link java.util.Collection
  75  * Collection} interface, and that its persistence is implemented atop
  76  * {@code java.io}.  Suppose the internals of the {@code add} method
  77  * can throw an {@link java.io.IOException IOException}.  The implementation
  78  * can communicate the details of the {@code IOException} to its caller
  79  * while conforming to the {@code Collection} interface by wrapping the
  80  * {@code IOException} in an appropriate unchecked exception.  (The
  81  * specification for the persistent collection should indicate that it is
  82  * capable of throwing such exceptions.)
  83  *
  84  * <p>A cause can be associated with a throwable in two ways: via a
  85  * constructor that takes the cause as an argument, or via the
  86  * {@link #initCause(Throwable)} method.  New throwable classes that
  87  * wish to allow causes to be associated with them should provide constructors
  88  * that take a cause and delegate (perhaps indirectly) to one of the
  89  * {@code Throwable} constructors that takes a cause.  For example:
  90  * <pre>
  91  *     try {
  92  *         lowLevelOp();
  93  *     } catch (LowLevelException le) {
  94  *         throw new HighLevelException(le);  // Chaining-aware constructor
  95  *     }
  96  * </pre>
  97  * Because the {@code initCause} method is public, it allows a cause to be
  98  * associated with any throwable, even a "legacy throwable" whose
  99  * implementation predates the addition of the exception chaining mechanism to
 100  * {@code Throwable}. For example:
 101  * <pre>
 102  *     try {
 103  *         lowLevelOp();
 104  *     } catch (LowLevelException le) {
 105  *         throw (HighLevelException)
 106  *               new HighLevelException().initCause(le);  // Legacy constructor
 107  *     }
 108  * </pre>
 109  *
 110  * <p>Prior to release 1.4, there were many throwables that had their own
 111  * non-standard exception chaining mechanisms (
 112  * {@link ExceptionInInitializerError}, {@link ClassNotFoundException},
 113  * {@link java.lang.reflect.UndeclaredThrowableException},
 114  * {@link java.lang.reflect.InvocationTargetException},
 115  * {@link java.io.WriteAbortedException},
 116  * {@link java.security.PrivilegedActionException},
 117  * {@link java.awt.print.PrinterIOException},
 118  * {@link java.rmi.RemoteException} and
 119  * {@link javax.naming.NamingException}).
 120  * All of these throwables have been retrofitted to
 121  * use the standard exception chaining mechanism, while continuing to
 122  * implement their "legacy" chaining mechanisms for compatibility.
 123  *
 124  * <p>Further, as of release 1.4, many general purpose {@code Throwable}
 125  * classes (for example {@link Exception}, {@link RuntimeException},
 126  * {@link Error}) have been retrofitted with constructors that take
 127  * a cause.  This was not strictly necessary, due to the existence of the
 128  * {@code initCause} method, but it is more convenient and expressive to
 129  * delegate to a constructor that takes a cause.
 130  *
 131  * <p>By convention, class {@code Throwable} and its subclasses have two
 132  * constructors, one that takes no arguments and one that takes a
 133  * {@code String} argument that can be used to produce a detail message.
 134  * Further, those subclasses that might likely have a cause associated with
 135  * them should have two more constructors, one that takes a
 136  * {@code Throwable} (the cause), and one that takes a
 137  * {@code String} (the detail message) and a {@code Throwable} (the
 138  * cause).
 139  *
 140  * <p>Also introduced in release 1.4 is the {@link #getStackTrace()} method,
 141  * which allows programmatic access to the stack trace information that was
 142  * previously available only in text form, via the various forms of the
 143  * {@link #printStackTrace()} method.  This information has been added to the
 144  * <i>serialized representation</i> of this class so {@code getStackTrace}
 145  * and {@code printStackTrace} will operate properly on a throwable that
 146  * was obtained by deserialization.
 147  *
 148  * @author  unascribed
 149  * @author  Josh Bloch (Added exception chaining and programmatic access to
 150  *          stack trace in 1.4.)
 151  * @jls3 11.2 Compile-Time Checking of Exceptions
 152  * @since JDK1.0
 153  */
 154 public class Throwable implements Serializable {
 155     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 156     private static final long serialVersionUID = -3042686055658047285L;
 157 
 158     /**
 159      * Native code saves some indication of the stack backtrace in this slot.
 160      */
 161     private transient Object backtrace;
 162 
 163     /**
 164      * Specific details about the Throwable.  For example, for
 165      * {@code FileNotFoundException}, this contains the name of
 166      * the file that could not be found.
 167      *
 168      * @serial
 169      */
 170     private String detailMessage;
 171 
 172     /*
 173      * To allow Throwable objects to be made immutable and safely
 174      * reused by the JVM, such as pre-allocated OutOfMemoryErrors, the
 175      * fields of Throwable that are writable in response to user
 176      * actions, cause and suppressedExceptions, obey the following
 177      * protocol:
 178      *
 179      * 1) The fields are initialized to a non-null sentinel value
 180      * which indicates the value has logically not been set.
 181      *
 182      * 2) Writing a null to the field indicates further writes
 183      * are forbidden
 184      * 
 185      * 3) The sentinel value may be replaced with another non-null
 186      * value.
 187      *
 188      * Implementations of the HotSpot JVM have preallocated
 189      * OutOfMemoryError objects to provide for better diagnosability
 190      * of that situation.  These objects are created without calling
 191      * the constructor for that class and the fields in question are
 192      * initialized to null.  To support this capability, any new
 193      * fields added to Throwable that require being initialized to a
 194      * non-null value require a coordinated JVM change.
 195      */
 196 
 197     /**
 198      * The throwable that caused this throwable to get thrown, or null if this
 199      * throwable was not caused by another throwable, or if the causative
 200      * throwable is unknown.  If this field is equal to this throwable itself,
 201      * it indicates that the cause of this throwable has not yet been
 202      * initialized.
 203      *
 204      * @serial
 205      * @since 1.4
 206      */
 207     private Throwable cause = this;
 208 
 209     /**
 210      * The stack trace, as returned by {@link #getStackTrace()}.
 211      *
 212      * @serial
 213      * @since 1.4
 214      */
 215     private StackTraceElement[] stackTrace;
 216 
 217     // Setting this static field introduces an acceptable
 218     // initialization dependency on a few java.util classes.
 219     private static final List<Throwable> suppressedSentinel =
 220         Collections.unmodifiableList(new ArrayList<Throwable>(0));
 221 
 222     /**
 223      * The list of suppressed exceptions, as returned by {@link
 224      * #getSuppressed()}.  The list is initialized to a zero-element
 225      * unmodifiable sentinel list.  When a serialized Throwable is
 226      * read in, if the {@code suppressedExceptions} field points to a
 227      * zero-element list, the field is reset to the sentinel value.
 228      *
 229      * @serial
 230      * @since 1.7
 231      */
 232     private List<Throwable> suppressedExceptions = suppressedSentinel;
 233 
 234     /** Message for trying to suppress a null exception. */
 235     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
 236 
 237     /** Message for trying to suppress oneself. */
 238     private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
 239 
 240     /** Caption  for labeling causative exception stack traces */
 241     private static final String CAUSE_CAPTION = "Caused by: ";
 242 
 243     /** Caption for labeling suppressed exception stack traces */
 244     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
 245 
 246     /**
 247      * Constructs a new throwable with {@code null} as its detail message.
 248      * The cause is not initialized, and may subsequently be initialized by a
 249      * call to {@link #initCause}.
 250      *
 251      * <p>The {@link #fillInStackTrace()} method is called to initialize
 252      * the stack trace data in the newly created throwable.
 253      */
 254     public Throwable() {
 255         fillInStackTrace();
 256     }
 257 
 258     /**
 259      * Constructs a new throwable with the specified detail message.  The
 260      * cause is not initialized, and may subsequently be initialized by
 261      * a call to {@link #initCause}.
 262      *
 263      * <p>The {@link #fillInStackTrace()} method is called to initialize
 264      * the stack trace data in the newly created throwable.
 265      *
 266      * @param   message   the detail message. The detail message is saved for
 267      *          later retrieval by the {@link #getMessage()} method.
 268      */
 269     public Throwable(String message) {
 270         fillInStackTrace();
 271         detailMessage = message;
 272     }
 273 
 274     /**
 275      * Constructs a new throwable with the specified detail message and
 276      * cause.  <p>Note that the detail message associated with
 277      * {@code cause} is <i>not</i> automatically incorporated in
 278      * this throwable's detail message.
 279      *
 280      * <p>The {@link #fillInStackTrace()} method is called to initialize
 281      * the stack trace data in the newly created throwable.
 282      *
 283      * @param  message the detail message (which is saved for later retrieval
 284      *         by the {@link #getMessage()} method).
 285      * @param  cause the cause (which is saved for later retrieval by the
 286      *         {@link #getCause()} method).  (A {@code null} value is
 287      *         permitted, and indicates that the cause is nonexistent or
 288      *         unknown.)
 289      * @since  1.4
 290      */
 291     public Throwable(String message, Throwable cause) {
 292         fillInStackTrace();
 293         detailMessage = message;
 294         this.cause = cause;
 295     }
 296 
 297     /**
 298      * Constructs a new throwable with the specified cause and a detail
 299      * message of {@code (cause==null ? null : cause.toString())} (which
 300      * typically contains the class and detail message of {@code cause}).
 301      * This constructor is useful for throwables that are little more than
 302      * wrappers for other throwables (for example, {@link
 303      * java.security.PrivilegedActionException}).
 304      *
 305      * <p>The {@link #fillInStackTrace()} method is called to initialize
 306      * the stack trace data in the newly created throwable.
 307      *
 308      * @param  cause the cause (which is saved for later retrieval by the
 309      *         {@link #getCause()} method).  (A {@code null} value is
 310      *         permitted, and indicates that the cause is nonexistent or
 311      *         unknown.)
 312      * @since  1.4
 313      */
 314     public Throwable(Throwable cause) {
 315         fillInStackTrace();
 316         detailMessage = (cause==null ? null : cause.toString());
 317         this.cause = cause;
 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 
 751         return stackTrace;
 752     }
 753 
 754     /**
 755      * Sets the stack trace elements that will be returned by
 756      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
 757      * and related methods.
 758      *
 759      * This method, which is designed for use by RPC frameworks and other
 760      * advanced systems, allows the client to override the default
 761      * stack trace that is either generated by {@link #fillInStackTrace()}
 762      * when a throwable is constructed or deserialized when a throwable is
 763      * read from a serialization stream.
 764      *
 765      * @param   stackTrace the stack trace elements to be associated with
 766      * this {@code Throwable}.  The specified array is copied by this
 767      * call; changes in the specified array after the method invocation
 768      * returns will have no affect on this {@code Throwable}'s stack
 769      * trace.
 770      *
 771      * @throws NullPointerException if {@code stackTrace} is
 772      *         {@code null}, or if any of the elements of
 773      *         {@code stackTrace} are {@code null}
 774      *
 775      * @since  1.4
 776      */
 777     public void setStackTrace(StackTraceElement[] stackTrace) {
 778         StackTraceElement[] defensiveCopy = stackTrace.clone();
 779         for (int i = 0; i < defensiveCopy.length; i++) {
 780             if (defensiveCopy[i] == null)
 781                 throw new NullPointerException("stackTrace[" + i + "]");
 782         }
 783 
 784         synchronized (this) {
 785             this.stackTrace = defensiveCopy;
 786         }
 787     }
 788 
 789     /**
 790      * Returns the number of elements in the stack trace (or 0 if the stack
 791      * trace is unavailable).
 792      *
 793      * package-protection for use by SharedSecrets.
 794      */
 795     native int getStackTraceDepth();
 796 
 797     /**
 798      * Returns the specified element of the stack trace.
 799      *
 800      * package-protection for use by SharedSecrets.
 801      *
 802      * @param index index of the element to return.
 803      * @throws IndexOutOfBoundsException if {@code index < 0 ||
 804      *         index >= getStackTraceDepth() }
 805      */
 806     native StackTraceElement getStackTraceElement(int index);
 807 
 808     /**
 809      * Read a {@code Throwable} from a stream, enforcing
 810      * well-formedness constraints on fields.  Null entries and
 811      * self-pointers are not allowed in the list of {@code
 812      * suppressedExceptions}.  Null entries are not allowed for stack
 813      * trace elements. 
 814      *
 815      * Note that there are no constraints on the value the {@code
 816      * cause} field can hold; both {@code null} and this are valid
 817      * values for the field.
 818      */
 819     private void readObject(ObjectInputStream s)
 820         throws IOException, ClassNotFoundException {
 821         s.defaultReadObject();     // read in all fields
 822         List<Throwable> suppressed = null;
 823         if (suppressedExceptions != null &&
 824             !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
 825             suppressed = new ArrayList<Throwable>(1);
 826             for (Throwable t : suppressedExceptions) {
 827                 // Enforce constraints on suppressed exceptions in
 828                 // case of corrupt or malicious stream.
 829                 if (t == null)
 830                     throw new NullPointerException(NULL_CAUSE_MESSAGE);
 831                 if (t == this)
 832                     throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 833                 suppressed.add(t);
 834             }
 835         }
 836 
 837         // If suppressed is a zero-length list, use the sentinel
 838         // value.
 839         if (suppressed != null && suppressed.isEmpty())
 840             suppressedExceptions = suppressedSentinel;
 841         else
 842             suppressedExceptions = suppressed;
 843 
 844         if (stackTrace != null) {
 845             for(StackTraceElement ste : stackTrace) {
 846                 if (ste == null)
 847                     throw new NullPointerException("null StackTraceElement in serial stream. ");
 848             }
 849         } else { // Treat a null stack trace as a missing stack trace
 850             stackTrace = new StackTraceElement[0];
 851         }
 852     }
 853 
 854     /**
 855      * Write a {@code Throwable} object to a stream.  The stack trace
 856      * will be non-{@code null}.
 857      */
 858     private synchronized void writeObject(ObjectOutputStream s)
 859         throws IOException {
 860         getOurStackTrace();  // Ensure that stackTrace field is initialized.
 861         s.defaultWriteObject();
 862     }
 863 
 864     /**
 865      * Adds the specified exception to the list of exceptions that
 866      * were suppressed, typically by the {@code try}-with-resources
 867      * statement, in order to deliver this exception.
 868      *
 869      * If the first exception to be suppressed is {@code null}, that
 870      * indicates suppressed exception information will <em>not</em> be
 871      * recorded for this exception.  Subsequent calls to this method
 872      * will not record any suppressed exceptions.  Otherwise,
 873      * attempting to suppress {@code null} after an exception has
 874      * already been successfully suppressed results in a {@code
 875      * NullPointerException}.
 876      *
 877      * <p>Note that when one exception {@linkplain
 878      * #initCause(Throwable) causes} another exception, the first
 879      * exception is usually caught and then the second exception is
 880      * thrown in response.  In contrast, when one exception suppresses
 881      * another, two exceptions are thrown in sibling code blocks, such
 882      * as in a {@code try} block and in its {@code finally} block, and
 883      * control flow can only continue with one exception so the second
 884      * is recorded as a suppressed exception of the first.
 885      *
 886      * @param exception the exception to be added to the list of
 887      *        suppressed exceptions
 888      * @throws IllegalArgumentException if {@code exception} is this
 889      *         throwable; a throwable cannot suppress itself.
 890      * @throws NullPointerException if {@code exception} is null and
 891      *         an exception has already been suppressed by this exception
 892      * @since 1.7
 893      */
 894     public synchronized void addSuppressed(Throwable exception) {
 895         if (exception == this)
 896             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 897 
 898         if (exception == null) {
 899             if (suppressedExceptions == suppressedSentinel) {
 900                 suppressedExceptions = null; // No suppression information recorded
 901                 return;
 902             } else
 903                 throw new NullPointerException(NULL_CAUSE_MESSAGE);
 904         } else {
 905             assert exception != null && exception != this;
 906 
 907             if (suppressedExceptions == null) // Suppressed exceptions not recorded
 908                 return;
 909 
 910             if (suppressedExceptions == suppressedSentinel)
 911                 suppressedExceptions = new ArrayList<Throwable>(1);
 912 
 913             assert suppressedExceptions != suppressedSentinel;
 914 
 915             suppressedExceptions.add(exception);
 916         }
 917     }
 918 
 919     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 920 
 921     /**
 922      * Returns an array containing all of the exceptions that were
 923      * suppressed, typically by the {@code try}-with-resources
 924      * statement, in order to deliver this exception.
 925      *
 926      * If no exceptions were suppressed, an empty array is returned.
 927      *
 928      * @return an array containing all of the exceptions that were
 929      *         suppressed to deliver this exception.
 930      * @since 1.7
 931      */
 932     public synchronized Throwable[] getSuppressed() {
 933         if (suppressedExceptions == suppressedSentinel ||
 934             suppressedExceptions == null)
 935             return EMPTY_THROWABLE_ARRAY;
 936         else
 937             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 938     }
 939 }