1 /*
   2  * Copyright (c) 1994, 2006, 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</code> 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</code> statement. Similarly, only
  35  * this class or one of its subclasses can be the argument type in a
  36  * <code>catch</code> 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  * <tt>java.io</tt>.  Suppose the internals of the <tt>add</tt> method
  77  * can throw an {@link java.io.IOException IOException}.  The implementation
  78  * can communicate the details of the <tt>IOException</tt> to its caller
  79  * while conforming to the <tt>Collection</tt> interface by wrapping the
  80  * <tt>IOException</tt> 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  * <tt>Throwable</tt> 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 <tt>initCause</tt> 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  * <tt>Throwable</tt>. 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 <tt>Throwable</tt>
 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  * <tt>initCause</tt> 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</code> and its subclasses have two
 132  * constructors, one that takes no arguments and one that takes a
 133  * <code>String</code> 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</code> (the cause), and one that takes a
 137  * <code>String</code> (the detail message) and a <code>Throwable</code> (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 <tt>getStackTrace</tt>
 145  * and <tt>printStackTrace</tt> 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      * <tt>FileNotFoundException</tt>, this contains the name of
 166      * the file that could not be found.
 167      *
 168      * @serial
 169      */
 170     private String detailMessage;
 171 
 172     /**
 173      * The throwable that caused this throwable to get thrown, or null if this
 174      * throwable was not caused by another throwable, or if the causative
 175      * throwable is unknown.  If this field is equal to this throwable itself,
 176      * it indicates that the cause of this throwable has not yet been
 177      * initialized.
 178      *
 179      * @serial
 180      * @since 1.4
 181      */
 182     private Throwable cause = this;
 183 
 184     /**
 185      * The stack trace, as returned by {@link #getStackTrace()}.
 186      *
 187      * @serial
 188      * @since 1.4
 189      */
 190     private StackTraceElement[] stackTrace;
 191     /*
 192      * This field is lazily initialized on first use or serialization and
 193      * nulled out when fillInStackTrace is called.
 194      */
 195 
 196     /**
 197      * The list of suppressed exceptions, as returned by
 198      * {@link #getSuppressedExceptions()}.
 199      *
 200      * @serial
 201      * @since 1.7
 202      */
 203     private List<Throwable> suppressedExceptions = Collections.emptyList();
 204 
 205     /** Caption  for lableing causative exception stack traces */
 206     private static final String CAUSE_CAPTION = "Caused by: ";
 207 
 208     /** Caption for lableing suppressed exception stack traces */
 209     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
 210 
 211     /**
 212      * Constructs a new throwable with <code>null</code> 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</code> 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 <tt>null</tt> 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 <tt>(cause==null ? null : cause.toString())</tt> (which
 265      * typically contains the class and detail message of <tt>cause</tt>).
 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 <tt>null</tt> 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 <tt>Throwable</tt> instance
 289      *          (which may be <tt>null</tt>).
 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()</code>.
 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</code> 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 <tt>Throwable</tt>, 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 <tt>Throwable</tt>.  Note that it is <i>not</i>
 321      * necessary to override any of the <tt>PrintStackTrace</tt> methods,
 322      * all of which invoke the <tt>getCause</tt> method to determine the
 323      * cause of a throwable.
 324      *
 325      * @return  the cause of this throwable or <code>null</code> if the
 326      *          cause is nonexistent or unknown.
 327      * @since 1.4
 328      */
 329     public 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 <tt>null</tt> value is
 346      *         permitted, and indicates that the cause is nonexistent or
 347      *         unknown.)
 348      * @return  a reference to this <code>Throwable</code> instance.
 349      * @throws IllegalArgumentException if <code>cause</code> 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 <tt>getLocalizedMessage</tt> returns <tt>null</tt>, 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</code> object on the error output stream that is
 390      * the value of the field <code>System.err</code>. 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 <tt>"..."</tt>.
 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 automatic
 490      * resource management blocks). 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</code> 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         synchronized (s.lock()) {
 550             // Print our stack trace
 551             s.println(this);
 552             StackTraceElement[] trace = getOurStackTrace();
 553             for (StackTraceElement traceElement : trace)
 554                 s.println("\tat " + traceElement);
 555 
 556             // Print suppressed exceptions, if any
 557             for (Throwable se : suppressedExceptions)
 558                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t");
 559 
 560             // Print cause, if any
 561             Throwable ourCause = getCause();
 562             if (ourCause != null)
 563                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "");
 564         }
 565     }
 566 
 567     /**
 568      * Print our stack trace as an enclosed exception for the specified
 569      * stack trace.
 570      */
 571     private void printEnclosedStackTrace(PrintStreamOrWriter s,
 572             StackTraceElement[] enclosingTrace, String caption, String prefix) {
 573         assert Thread.holdsLock(s.lock());
 574 
 575         // Compute number of frames in common between this and enclosing trace
 576         StackTraceElement[] trace = getOurStackTrace();
 577         int m = trace.length-1, n = enclosingTrace.length-1;
 578         while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
 579             m--; n--;
 580         }
 581         int framesInCommon = trace.length - 1 - m;
 582 
 583         // Print our stack trace
 584         s.println(prefix + caption + this);
 585         for (int i = 0; i <= m; i++)
 586             s.println(prefix + "\tat " + trace[i]);
 587         if (framesInCommon != 0)
 588             s.println(prefix + "\t... " + framesInCommon + " more");
 589 
 590         // Print suppressed exceptions, if any
 591         for (Throwable se : suppressedExceptions)
 592             se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
 593                     prefix +"\t");
 594 
 595         // Print cause, if any
 596         Throwable ourCause = getCause();
 597         if (ourCause != null)
 598             ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix);
 599     }
 600 
 601     /**
 602      * Prints this throwable and its backtrace to the specified
 603      * print writer.
 604      *
 605      * @param s <code>PrintWriter</code> to use for output
 606      * @since   JDK1.1
 607      */
 608     public void printStackTrace(PrintWriter s) {
 609         printStackTrace(new WrappedPrintWriter(s));
 610     }
 611 
 612     /**
 613      * Wrapper class for PrintStream and PrintWirter to enable a single
 614      * implementation of printStackTrace.
 615      */
 616     private abstract static class PrintStreamOrWriter {
 617         /** Returns the object to be locked when using this StreamOrWriter */
 618         abstract Object lock();
 619 
 620         /** Prints the specified string as a line on this StreamOrWriter */
 621         abstract void println(Object o);
 622     }
 623 
 624     private static class WrappedPrintStream extends PrintStreamOrWriter {
 625         private final PrintStream printStream;
 626 
 627         WrappedPrintStream(PrintStream printStream) {
 628             this.printStream = printStream;
 629         }
 630 
 631         Object lock() {
 632             return printStream;
 633         }
 634 
 635         void println(Object o) {
 636             printStream.println(o);
 637         }
 638     }
 639 
 640     private static class WrappedPrintWriter extends PrintStreamOrWriter {
 641         private final PrintWriter printWriter;
 642 
 643         WrappedPrintWriter(PrintWriter printWriter) {
 644             this.printWriter = printWriter;
 645         }
 646 
 647         Object lock() {
 648             return printWriter;
 649         }
 650 
 651         void println(Object o) {
 652             printWriter.println(o);
 653         }
 654     }
 655 
 656     /**
 657      * Fills in the execution stack trace. This method records within this
 658      * <code>Throwable</code> object information about the current state of
 659      * the stack frames for the current thread.
 660      *
 661      * @return  a reference to this <code>Throwable</code> instance.
 662      * @see     java.lang.Throwable#printStackTrace()
 663      */
 664     public synchronized native Throwable fillInStackTrace();
 665 
 666     /**
 667      * Provides programmatic access to the stack trace information printed by
 668      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
 669      * each representing one stack frame.  The zeroth element of the array
 670      * (assuming the array's length is non-zero) represents the top of the
 671      * stack, which is the last method invocation in the sequence.  Typically,
 672      * this is the point at which this throwable was created and thrown.
 673      * The last element of the array (assuming the array's length is non-zero)
 674      * represents the bottom of the stack, which is the first method invocation
 675      * in the sequence.
 676      *
 677      * <p>Some virtual machines may, under some circumstances, omit one
 678      * or more stack frames from the stack trace.  In the extreme case,
 679      * a virtual machine that has no stack trace information concerning
 680      * this throwable is permitted to return a zero-length array from this
 681      * method.  Generally speaking, the array returned by this method will
 682      * contain one element for every frame that would be printed by
 683      * <tt>printStackTrace</tt>.
 684      *
 685      * @return an array of stack trace elements representing the stack trace
 686      *         pertaining to this throwable.
 687      * @since  1.4
 688      */
 689     public StackTraceElement[] getStackTrace() {
 690         return getOurStackTrace().clone();
 691     }
 692 
 693     private synchronized StackTraceElement[] getOurStackTrace() {
 694         // Initialize stack trace if this is the first call to this method
 695         if (stackTrace == null) {
 696             int depth = getStackTraceDepth();
 697             stackTrace = new StackTraceElement[depth];
 698             for (int i=0; i < depth; i++)
 699                 stackTrace[i] = getStackTraceElement(i);
 700         }
 701         return stackTrace;
 702     }
 703 
 704     /**
 705      * Sets the stack trace elements that will be returned by
 706      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
 707      * and related methods.
 708      *
 709      * This method, which is designed for use by RPC frameworks and other
 710      * advanced systems, allows the client to override the default
 711      * stack trace that is either generated by {@link #fillInStackTrace()}
 712      * when a throwable is constructed or deserialized when a throwable is
 713      * read from a serialization stream.
 714      *
 715      * @param   stackTrace the stack trace elements to be associated with
 716      * this <code>Throwable</code>.  The specified array is copied by this
 717      * call; changes in the specified array after the method invocation
 718      * returns will have no affect on this <code>Throwable</code>'s stack
 719      * trace.
 720      *
 721      * @throws NullPointerException if <code>stackTrace</code> is
 722      *         <code>null</code>, or if any of the elements of
 723      *         <code>stackTrace</code> are <code>null</code>
 724      *
 725      * @since  1.4
 726      */
 727     public void setStackTrace(StackTraceElement[] stackTrace) {
 728         StackTraceElement[] defensiveCopy = stackTrace.clone();
 729         for (int i = 0; i < defensiveCopy.length; i++)
 730             if (defensiveCopy[i] == null)
 731                 throw new NullPointerException("stackTrace[" + i + "]");
 732 
 733         this.stackTrace = defensiveCopy;
 734     }
 735 
 736     /**
 737      * Returns the number of elements in the stack trace (or 0 if the stack
 738      * trace is unavailable).
 739      *
 740      * package-protection for use by SharedSecrets.
 741      */
 742     native int getStackTraceDepth();
 743 
 744     /**
 745      * Returns the specified element of the stack trace.
 746      *
 747      * package-protection for use by SharedSecrets.
 748      *
 749      * @param index index of the element to return.
 750      * @throws IndexOutOfBoundsException if <tt>index &lt; 0 ||
 751      *         index &gt;= getStackTraceDepth() </tt>
 752      */
 753     native StackTraceElement getStackTraceElement(int index);
 754 
 755     private synchronized void writeObject(java.io.ObjectOutputStream s)
 756         throws IOException
 757     {
 758         getOurStackTrace();  // Ensure that stackTrace field is initialized.
 759         s.defaultWriteObject();
 760     }
 761 
 762     /**
 763      * Adds the specified exception to the list of exceptions that
 764      * were suppressed, typically by the automatic resource management
 765      * statement, in order to deliver this exception.
 766      *
 767      * @param exception the exception to be added to the list of
 768      *        suppressed exceptions
 769      * @throws NullPointerException if {@code exception} is null
 770      * @since 1.7
 771      */
 772     public synchronized void addSuppressedException(Throwable exception) {
 773         if (exception == null)
 774             throw new NullPointerException();
 775 
 776         if (suppressedExceptions.size() == 0)
 777             suppressedExceptions = new ArrayList<Throwable>();
 778         suppressedExceptions.add(exception);
 779     }
 780 
 781     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 782     
 783     /**
 784      * Returns an array containing all of the exceptions that were
 785      * suppressed, typically by the automatic resource management
 786      * statement, in order to deliver this exception.
 787      *
 788      * @return an array containing all of the exceptions that were
 789      *         suppressed to deliver this exception.
 790      * @since 1.7
 791      */
 792     public Throwable[] getSuppressedExceptions() {
 793         return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 794     }
 795 }