emul/src/main/java/java/lang/Throwable.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 28 Sep 2012 17:59:03 +0200
branchemul
changeset 49 0a115f1c6f3c
child 51 506ef276a0db
permissions -rw-r--r--
Bringing in core Java classes as of OpenJDK tag jdk7-b147
     1 /*
     2  * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 
    26 package java.lang;
    27 import  java.io.*;
    28 import  java.util.*;
    29 
    30 /**
    31  * The {@code Throwable} class is the superclass of all errors and
    32  * exceptions in the Java language. Only objects that are instances of this
    33  * class (or one of its subclasses) are thrown by the Java Virtual Machine or
    34  * can be thrown by the Java {@code throw} statement. Similarly, only
    35  * this class or one of its subclasses can be the argument type in a
    36  * {@code catch} clause.
    37  *
    38  * For the purposes of compile-time checking of exceptions, {@code
    39  * Throwable} and any subclass of {@code Throwable} that is not also a
    40  * subclass of either {@link RuntimeException} or {@link Error} are
    41  * regarded as checked exceptions.
    42  *
    43  * <p>Instances of two subclasses, {@link java.lang.Error} and
    44  * {@link java.lang.Exception}, are conventionally used to indicate
    45  * that exceptional situations have occurred. Typically, these instances
    46  * are freshly created in the context of the exceptional situation so
    47  * as to include relevant information (such as stack trace data).
    48  *
    49  * <p>A throwable contains a snapshot of the execution stack of its
    50  * thread at the time it was created. It can also contain a message
    51  * string that gives more information about the error. Over time, a
    52  * throwable can {@linkplain Throwable#addSuppressed suppress} other
    53  * throwables from being propagated.  Finally, the throwable can also
    54  * contain a <i>cause</i>: another throwable that caused this
    55  * throwable to be constructed.  The recording of this causal information
    56  * is referred to as the <i>chained exception</i> facility, as the
    57  * cause can, itself, have a cause, and so on, leading to a "chain" of
    58  * exceptions, each caused by another.
    59  *
    60  * <p>One reason that a throwable may have a cause is that the class that
    61  * throws it is built atop a lower layered abstraction, and an operation on
    62  * the upper layer fails due to a failure in the lower layer.  It would be bad
    63  * design to let the throwable thrown by the lower layer propagate outward, as
    64  * it is generally unrelated to the abstraction provided by the upper layer.
    65  * Further, doing so would tie the API of the upper layer to the details of
    66  * its implementation, assuming the lower layer's exception was a checked
    67  * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
    68  * cause) allows the upper layer to communicate the details of the failure to
    69  * its caller without incurring either of these shortcomings.  It preserves
    70  * the flexibility to change the implementation of the upper layer without
    71  * changing its API (in particular, the set of exceptions thrown by its
    72  * methods).
    73  *
    74  * <p>A second reason that a throwable may have a cause is that the method
    75  * that throws it must conform to a general-purpose interface that does not
    76  * permit the method to throw the cause directly.  For example, suppose
    77  * a persistent collection conforms to the {@link java.util.Collection
    78  * Collection} interface, and that its persistence is implemented atop
    79  * {@code java.io}.  Suppose the internals of the {@code add} method
    80  * can throw an {@link java.io.IOException IOException}.  The implementation
    81  * can communicate the details of the {@code IOException} to its caller
    82  * while conforming to the {@code Collection} interface by wrapping the
    83  * {@code IOException} in an appropriate unchecked exception.  (The
    84  * specification for the persistent collection should indicate that it is
    85  * capable of throwing such exceptions.)
    86  *
    87  * <p>A cause can be associated with a throwable in two ways: via a
    88  * constructor that takes the cause as an argument, or via the
    89  * {@link #initCause(Throwable)} method.  New throwable classes that
    90  * wish to allow causes to be associated with them should provide constructors
    91  * that take a cause and delegate (perhaps indirectly) to one of the
    92  * {@code Throwable} constructors that takes a cause.
    93  *
    94  * Because the {@code initCause} method is public, it allows a cause to be
    95  * associated with any throwable, even a "legacy throwable" whose
    96  * implementation predates the addition of the exception chaining mechanism to
    97  * {@code Throwable}.
    98  *
    99  * <p>By convention, class {@code Throwable} and its subclasses have two
   100  * constructors, one that takes no arguments and one that takes a
   101  * {@code String} argument that can be used to produce a detail message.
   102  * Further, those subclasses that might likely have a cause associated with
   103  * them should have two more constructors, one that takes a
   104  * {@code Throwable} (the cause), and one that takes a
   105  * {@code String} (the detail message) and a {@code Throwable} (the
   106  * cause).
   107  *
   108  * @author  unascribed
   109  * @author  Josh Bloch (Added exception chaining and programmatic access to
   110  *          stack trace in 1.4.)
   111  * @jls 11.2 Compile-Time Checking of Exceptions
   112  * @since JDK1.0
   113  */
   114 public class Throwable implements Serializable {
   115     /** use serialVersionUID from JDK 1.0.2 for interoperability */
   116     private static final long serialVersionUID = -3042686055658047285L;
   117 
   118     /**
   119      * Native code saves some indication of the stack backtrace in this slot.
   120      */
   121     private transient Object backtrace;
   122 
   123     /**
   124      * Specific details about the Throwable.  For example, for
   125      * {@code FileNotFoundException}, this contains the name of
   126      * the file that could not be found.
   127      *
   128      * @serial
   129      */
   130     private String detailMessage;
   131 
   132 
   133     /**
   134      * Holder class to defer initializing sentinel objects only used
   135      * for serialization.
   136      */
   137     private static class SentinelHolder {
   138         /**
   139          * {@linkplain #setStackTrace(StackTraceElement[]) Setting the
   140          * stack trace} to a one-element array containing this sentinel
   141          * value indicates future attempts to set the stack trace will be
   142          * ignored.  The sentinal is equal to the result of calling:<br>
   143          * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
   144          */
   145         public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
   146             new StackTraceElement("", "", null, Integer.MIN_VALUE);
   147 
   148         /**
   149          * Sentinel value used in the serial form to indicate an immutable
   150          * stack trace.
   151          */
   152         public static final StackTraceElement[] STACK_TRACE_SENTINEL =
   153             new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
   154     }
   155 
   156     /**
   157      * A shared value for an empty stack.
   158      */
   159     private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];
   160 
   161     /*
   162      * To allow Throwable objects to be made immutable and safely
   163      * reused by the JVM, such as OutOfMemoryErrors, fields of
   164      * Throwable that are writable in response to user actions, cause,
   165      * stackTrace, and suppressedExceptions obey the following
   166      * protocol:
   167      *
   168      * 1) The fields are initialized to a non-null sentinel value
   169      * which indicates the value has logically not been set.
   170      *
   171      * 2) Writing a null to the field indicates further writes
   172      * are forbidden
   173      *
   174      * 3) The sentinel value may be replaced with another non-null
   175      * value.
   176      *
   177      * For example, implementations of the HotSpot JVM have
   178      * preallocated OutOfMemoryError objects to provide for better
   179      * diagnosability of that situation.  These objects are created
   180      * without calling the constructor for that class and the fields
   181      * in question are initialized to null.  To support this
   182      * capability, any new fields added to Throwable that require
   183      * being initialized to a non-null value require a coordinated JVM
   184      * change.
   185      */
   186 
   187     /**
   188      * The throwable that caused this throwable to get thrown, or null if this
   189      * throwable was not caused by another throwable, or if the causative
   190      * throwable is unknown.  If this field is equal to this throwable itself,
   191      * it indicates that the cause of this throwable has not yet been
   192      * initialized.
   193      *
   194      * @serial
   195      * @since 1.4
   196      */
   197     private Throwable cause = this;
   198 
   199     /**
   200      * The stack trace, as returned by {@link #getStackTrace()}.
   201      *
   202      * The field is initialized to a zero-length array.  A {@code
   203      * null} value of this field indicates subsequent calls to {@link
   204      * #setStackTrace(StackTraceElement[])} and {@link
   205      * #fillInStackTrace()} will be be no-ops.
   206      *
   207      * @serial
   208      * @since 1.4
   209      */
   210     private StackTraceElement[] stackTrace = UNASSIGNED_STACK;
   211 
   212     // Setting this static field introduces an acceptable
   213     // initialization dependency on a few java.util classes.
   214     private static final List<Throwable> SUPPRESSED_SENTINEL =
   215         Collections.unmodifiableList(new ArrayList<Throwable>(0));
   216 
   217     /**
   218      * The list of suppressed exceptions, as returned by {@link
   219      * #getSuppressed()}.  The list is initialized to a zero-element
   220      * unmodifiable sentinel list.  When a serialized Throwable is
   221      * read in, if the {@code suppressedExceptions} field points to a
   222      * zero-element list, the field is reset to the sentinel value.
   223      *
   224      * @serial
   225      * @since 1.7
   226      */
   227     private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
   228 
   229     /** Message for trying to suppress a null exception. */
   230     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
   231 
   232     /** Message for trying to suppress oneself. */
   233     private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
   234 
   235     /** Caption  for labeling causative exception stack traces */
   236     private static final String CAUSE_CAPTION = "Caused by: ";
   237 
   238     /** Caption for labeling suppressed exception stack traces */
   239     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
   240 
   241     /**
   242      * Constructs a new throwable with {@code null} as its detail message.
   243      * The cause is not initialized, and may subsequently be initialized by a
   244      * call to {@link #initCause}.
   245      *
   246      * <p>The {@link #fillInStackTrace()} method is called to initialize
   247      * the stack trace data in the newly created throwable.
   248      */
   249     public Throwable() {
   250         fillInStackTrace();
   251     }
   252 
   253     /**
   254      * Constructs a new throwable with the specified detail message.  The
   255      * cause is not initialized, and may subsequently be initialized by
   256      * a call to {@link #initCause}.
   257      *
   258      * <p>The {@link #fillInStackTrace()} method is called to initialize
   259      * the stack trace data in the newly created throwable.
   260      *
   261      * @param   message   the detail message. The detail message is saved for
   262      *          later retrieval by the {@link #getMessage()} method.
   263      */
   264     public Throwable(String message) {
   265         fillInStackTrace();
   266         detailMessage = message;
   267     }
   268 
   269     /**
   270      * Constructs a new throwable with the specified detail message and
   271      * cause.  <p>Note that the detail message associated with
   272      * {@code cause} is <i>not</i> automatically incorporated in
   273      * this throwable's detail message.
   274      *
   275      * <p>The {@link #fillInStackTrace()} method is called to initialize
   276      * the stack trace data in the newly created throwable.
   277      *
   278      * @param  message the detail message (which is saved for later retrieval
   279      *         by the {@link #getMessage()} method).
   280      * @param  cause the cause (which is saved for later retrieval by the
   281      *         {@link #getCause()} method).  (A {@code null} value is
   282      *         permitted, and indicates that the cause is nonexistent or
   283      *         unknown.)
   284      * @since  1.4
   285      */
   286     public Throwable(String message, Throwable cause) {
   287         fillInStackTrace();
   288         detailMessage = message;
   289         this.cause = cause;
   290     }
   291 
   292     /**
   293      * Constructs a new throwable with the specified cause and a detail
   294      * message of {@code (cause==null ? null : cause.toString())} (which
   295      * typically contains the class and detail message of {@code cause}).
   296      * This constructor is useful for throwables that are little more than
   297      * wrappers for other throwables (for example, {@link
   298      * java.security.PrivilegedActionException}).
   299      *
   300      * <p>The {@link #fillInStackTrace()} method is called to initialize
   301      * the stack trace data in the newly created throwable.
   302      *
   303      * @param  cause the cause (which is saved for later retrieval by the
   304      *         {@link #getCause()} method).  (A {@code null} value is
   305      *         permitted, and indicates that the cause is nonexistent or
   306      *         unknown.)
   307      * @since  1.4
   308      */
   309     public Throwable(Throwable cause) {
   310         fillInStackTrace();
   311         detailMessage = (cause==null ? null : cause.toString());
   312         this.cause = cause;
   313     }
   314 
   315     /**
   316      * Constructs a new throwable with the specified detail message,
   317      * cause, {@linkplain #addSuppressed suppression} enabled or
   318      * disabled, and writable stack trace enabled or disabled.  If
   319      * suppression is disabled, {@link #getSuppressed} for this object
   320      * will return a zero-length array and calls to {@link
   321      * #addSuppressed} that would otherwise append an exception to the
   322      * suppressed list will have no effect.  If the writable stack
   323      * trace is false, this constructor will not call {@link
   324      * #fillInStackTrace()}, a {@code null} will be written to the
   325      * {@code stackTrace} field, and subsequent calls to {@code
   326      * fillInStackTrace} and {@link
   327      * #setStackTrace(StackTraceElement[])} will not set the stack
   328      * trace.  If the writable stack trace is false, {@link
   329      * #getStackTrace} will return a zero length array.
   330      *
   331      * <p>Note that the other constructors of {@code Throwable} treat
   332      * suppression as being enabled and the stack trace as being
   333      * writable.  Subclasses of {@code Throwable} should document any
   334      * conditions under which suppression is disabled and document
   335      * conditions under which the stack trace is not writable.
   336      * Disabling of suppression should only occur in exceptional
   337      * circumstances where special requirements exist, such as a
   338      * virtual machine reusing exception objects under low-memory
   339      * situations.  Circumstances where a given exception object is
   340      * repeatedly caught and rethrown, such as to implement control
   341      * flow between two sub-systems, is another situation where
   342      * immutable throwable objects would be appropriate.
   343      *
   344      * @param  message the detail message.
   345      * @param cause the cause.  (A {@code null} value is permitted,
   346      * and indicates that the cause is nonexistent or unknown.)
   347      * @param enableSuppression whether or not suppression is enabled or disabled
   348      * @param writableStackTrace whether or not the stack trace should be
   349      *                           writable
   350      *
   351      * @see OutOfMemoryError
   352      * @see NullPointerException
   353      * @see ArithmeticException
   354      * @since 1.7
   355      */
   356     protected Throwable(String message, Throwable cause,
   357                         boolean enableSuppression,
   358                         boolean writableStackTrace) {
   359         if (writableStackTrace) {
   360             fillInStackTrace();
   361         } else {
   362             stackTrace = null;
   363         }
   364         detailMessage = message;
   365         this.cause = cause;
   366         if (!enableSuppression)
   367             suppressedExceptions = null;
   368     }
   369 
   370     /**
   371      * Returns the detail message string of this throwable.
   372      *
   373      * @return  the detail message string of this {@code Throwable} instance
   374      *          (which may be {@code null}).
   375      */
   376     public String getMessage() {
   377         return detailMessage;
   378     }
   379 
   380     /**
   381      * Creates a localized description of this throwable.
   382      * Subclasses may override this method in order to produce a
   383      * locale-specific message.  For subclasses that do not override this
   384      * method, the default implementation returns the same result as
   385      * {@code getMessage()}.
   386      *
   387      * @return  The localized description of this throwable.
   388      * @since   JDK1.1
   389      */
   390     public String getLocalizedMessage() {
   391         return getMessage();
   392     }
   393 
   394     /**
   395      * Returns the cause of this throwable or {@code null} if the
   396      * cause is nonexistent or unknown.  (The cause is the throwable that
   397      * caused this throwable to get thrown.)
   398      *
   399      * <p>This implementation returns the cause that was supplied via one of
   400      * the constructors requiring a {@code Throwable}, or that was set after
   401      * creation with the {@link #initCause(Throwable)} method.  While it is
   402      * typically unnecessary to override this method, a subclass can override
   403      * it to return a cause set by some other means.  This is appropriate for
   404      * a "legacy chained throwable" that predates the addition of chained
   405      * exceptions to {@code Throwable}.  Note that it is <i>not</i>
   406      * necessary to override any of the {@code PrintStackTrace} methods,
   407      * all of which invoke the {@code getCause} method to determine the
   408      * cause of a throwable.
   409      *
   410      * @return  the cause of this throwable or {@code null} if the
   411      *          cause is nonexistent or unknown.
   412      * @since 1.4
   413      */
   414     public synchronized Throwable getCause() {
   415         return (cause==this ? null : cause);
   416     }
   417 
   418     /**
   419      * Initializes the <i>cause</i> of this throwable to the specified value.
   420      * (The cause is the throwable that caused this throwable to get thrown.)
   421      *
   422      * <p>This method can be called at most once.  It is generally called from
   423      * within the constructor, or immediately after creating the
   424      * throwable.  If this throwable was created
   425      * with {@link #Throwable(Throwable)} or
   426      * {@link #Throwable(String,Throwable)}, this method cannot be called
   427      * even once.
   428      *
   429      * <p>An example of using this method on a legacy throwable type
   430      * without other support for setting the cause is:
   431      *
   432      * <pre>
   433      * try {
   434      *     lowLevelOp();
   435      * } catch (LowLevelException le) {
   436      *     throw (HighLevelException)
   437      *           new HighLevelException().initCause(le); // Legacy constructor
   438      * }
   439      * </pre>
   440      *
   441      * @param  cause the cause (which is saved for later retrieval by the
   442      *         {@link #getCause()} method).  (A {@code null} value is
   443      *         permitted, and indicates that the cause is nonexistent or
   444      *         unknown.)
   445      * @return  a reference to this {@code Throwable} instance.
   446      * @throws IllegalArgumentException if {@code cause} is this
   447      *         throwable.  (A throwable cannot be its own cause.)
   448      * @throws IllegalStateException if this throwable was
   449      *         created with {@link #Throwable(Throwable)} or
   450      *         {@link #Throwable(String,Throwable)}, or this method has already
   451      *         been called on this throwable.
   452      * @since  1.4
   453      */
   454     public synchronized Throwable initCause(Throwable cause) {
   455         if (this.cause != this)
   456             throw new IllegalStateException("Can't overwrite cause");
   457         if (cause == this)
   458             throw new IllegalArgumentException("Self-causation not permitted");
   459         this.cause = cause;
   460         return this;
   461     }
   462 
   463     /**
   464      * Returns a short description of this throwable.
   465      * The result is the concatenation of:
   466      * <ul>
   467      * <li> the {@linkplain Class#getName() name} of the class of this object
   468      * <li> ": " (a colon and a space)
   469      * <li> the result of invoking this object's {@link #getLocalizedMessage}
   470      *      method
   471      * </ul>
   472      * If {@code getLocalizedMessage} returns {@code null}, then just
   473      * the class name is returned.
   474      *
   475      * @return a string representation of this throwable.
   476      */
   477     public String toString() {
   478         String s = getClass().getName();
   479         String message = getLocalizedMessage();
   480         return (message != null) ? (s + ": " + message) : s;
   481     }
   482 
   483     /**
   484      * Prints this throwable and its backtrace to the
   485      * standard error stream. This method prints a stack trace for this
   486      * {@code Throwable} object on the error output stream that is
   487      * the value of the field {@code System.err}. The first line of
   488      * output contains the result of the {@link #toString()} method for
   489      * this object.  Remaining lines represent data previously recorded by
   490      * the method {@link #fillInStackTrace()}. The format of this
   491      * information depends on the implementation, but the following
   492      * example may be regarded as typical:
   493      * <blockquote><pre>
   494      * java.lang.NullPointerException
   495      *         at MyClass.mash(MyClass.java:9)
   496      *         at MyClass.crunch(MyClass.java:6)
   497      *         at MyClass.main(MyClass.java:3)
   498      * </pre></blockquote>
   499      * This example was produced by running the program:
   500      * <pre>
   501      * class MyClass {
   502      *     public static void main(String[] args) {
   503      *         crunch(null);
   504      *     }
   505      *     static void crunch(int[] a) {
   506      *         mash(a);
   507      *     }
   508      *     static void mash(int[] b) {
   509      *         System.out.println(b[0]);
   510      *     }
   511      * }
   512      * </pre>
   513      * The backtrace for a throwable with an initialized, non-null cause
   514      * should generally include the backtrace for the cause.  The format
   515      * of this information depends on the implementation, but the following
   516      * example may be regarded as typical:
   517      * <pre>
   518      * HighLevelException: MidLevelException: LowLevelException
   519      *         at Junk.a(Junk.java:13)
   520      *         at Junk.main(Junk.java:4)
   521      * Caused by: MidLevelException: LowLevelException
   522      *         at Junk.c(Junk.java:23)
   523      *         at Junk.b(Junk.java:17)
   524      *         at Junk.a(Junk.java:11)
   525      *         ... 1 more
   526      * Caused by: LowLevelException
   527      *         at Junk.e(Junk.java:30)
   528      *         at Junk.d(Junk.java:27)
   529      *         at Junk.c(Junk.java:21)
   530      *         ... 3 more
   531      * </pre>
   532      * Note the presence of lines containing the characters {@code "..."}.
   533      * These lines indicate that the remainder of the stack trace for this
   534      * exception matches the indicated number of frames from the bottom of the
   535      * stack trace of the exception that was caused by this exception (the
   536      * "enclosing" exception).  This shorthand can greatly reduce the length
   537      * of the output in the common case where a wrapped exception is thrown
   538      * from same method as the "causative exception" is caught.  The above
   539      * example was produced by running the program:
   540      * <pre>
   541      * public class Junk {
   542      *     public static void main(String args[]) {
   543      *         try {
   544      *             a();
   545      *         } catch(HighLevelException e) {
   546      *             e.printStackTrace();
   547      *         }
   548      *     }
   549      *     static void a() throws HighLevelException {
   550      *         try {
   551      *             b();
   552      *         } catch(MidLevelException e) {
   553      *             throw new HighLevelException(e);
   554      *         }
   555      *     }
   556      *     static void b() throws MidLevelException {
   557      *         c();
   558      *     }
   559      *     static void c() throws MidLevelException {
   560      *         try {
   561      *             d();
   562      *         } catch(LowLevelException e) {
   563      *             throw new MidLevelException(e);
   564      *         }
   565      *     }
   566      *     static void d() throws LowLevelException {
   567      *        e();
   568      *     }
   569      *     static void e() throws LowLevelException {
   570      *         throw new LowLevelException();
   571      *     }
   572      * }
   573      *
   574      * class HighLevelException extends Exception {
   575      *     HighLevelException(Throwable cause) { super(cause); }
   576      * }
   577      *
   578      * class MidLevelException extends Exception {
   579      *     MidLevelException(Throwable cause)  { super(cause); }
   580      * }
   581      *
   582      * class LowLevelException extends Exception {
   583      * }
   584      * </pre>
   585      * As of release 7, the platform supports the notion of
   586      * <i>suppressed exceptions</i> (in conjunction with the {@code
   587      * try}-with-resources statement). Any exceptions that were
   588      * suppressed in order to deliver an exception are printed out
   589      * beneath the stack trace.  The format of this information
   590      * depends on the implementation, but the following example may be
   591      * regarded as typical:
   592      *
   593      * <pre>
   594      * Exception in thread "main" java.lang.Exception: Something happened
   595      *  at Foo.bar(Foo.java:10)
   596      *  at Foo.main(Foo.java:5)
   597      *  Suppressed: Resource$CloseFailException: Resource ID = 0
   598      *          at Resource.close(Resource.java:26)
   599      *          at Foo.bar(Foo.java:9)
   600      *          ... 1 more
   601      * </pre>
   602      * Note that the "... n more" notation is used on suppressed exceptions
   603      * just at it is used on causes. Unlike causes, suppressed exceptions are
   604      * indented beyond their "containing exceptions."
   605      *
   606      * <p>An exception can have both a cause and one or more suppressed
   607      * exceptions:
   608      * <pre>
   609      * Exception in thread "main" java.lang.Exception: Main block
   610      *  at Foo3.main(Foo3.java:7)
   611      *  Suppressed: Resource$CloseFailException: Resource ID = 2
   612      *          at Resource.close(Resource.java:26)
   613      *          at Foo3.main(Foo3.java:5)
   614      *  Suppressed: Resource$CloseFailException: Resource ID = 1
   615      *          at Resource.close(Resource.java:26)
   616      *          at Foo3.main(Foo3.java:5)
   617      * Caused by: java.lang.Exception: I did it
   618      *  at Foo3.main(Foo3.java:8)
   619      * </pre>
   620      * Likewise, a suppressed exception can have a cause:
   621      * <pre>
   622      * Exception in thread "main" java.lang.Exception: Main block
   623      *  at Foo4.main(Foo4.java:6)
   624      *  Suppressed: Resource2$CloseFailException: Resource ID = 1
   625      *          at Resource2.close(Resource2.java:20)
   626      *          at Foo4.main(Foo4.java:5)
   627      *  Caused by: java.lang.Exception: Rats, you caught me
   628      *          at Resource2$CloseFailException.<init>(Resource2.java:45)
   629      *          ... 2 more
   630      * </pre>
   631      */
   632     public void printStackTrace() {
   633         printStackTrace(System.err);
   634     }
   635 
   636     /**
   637      * Prints this throwable and its backtrace to the specified print stream.
   638      *
   639      * @param s {@code PrintStream} to use for output
   640      */
   641     public void printStackTrace(PrintStream s) {
   642         printStackTrace(new WrappedPrintStream(s));
   643     }
   644 
   645     private void printStackTrace(PrintStreamOrWriter s) {
   646         // Guard against malicious overrides of Throwable.equals by
   647         // using a Set with identity equality semantics.
   648         Set<Throwable> dejaVu =
   649             Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
   650         dejaVu.add(this);
   651 
   652         synchronized (s.lock()) {
   653             // Print our stack trace
   654             s.println(this);
   655             StackTraceElement[] trace = getOurStackTrace();
   656             for (StackTraceElement traceElement : trace)
   657                 s.println("\tat " + traceElement);
   658 
   659             // Print suppressed exceptions, if any
   660             for (Throwable se : getSuppressed())
   661                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
   662 
   663             // Print cause, if any
   664             Throwable ourCause = getCause();
   665             if (ourCause != null)
   666                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
   667         }
   668     }
   669 
   670     /**
   671      * Print our stack trace as an enclosed exception for the specified
   672      * stack trace.
   673      */
   674     private void printEnclosedStackTrace(PrintStreamOrWriter s,
   675                                          StackTraceElement[] enclosingTrace,
   676                                          String caption,
   677                                          String prefix,
   678                                          Set<Throwable> dejaVu) {
   679         assert Thread.holdsLock(s.lock());
   680         if (dejaVu.contains(this)) {
   681             s.println("\t[CIRCULAR REFERENCE:" + this + "]");
   682         } else {
   683             dejaVu.add(this);
   684             // Compute number of frames in common between this and enclosing trace
   685             StackTraceElement[] trace = getOurStackTrace();
   686             int m = trace.length - 1;
   687             int n = enclosingTrace.length - 1;
   688             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
   689                 m--; n--;
   690             }
   691             int framesInCommon = trace.length - 1 - m;
   692 
   693             // Print our stack trace
   694             s.println(prefix + caption + this);
   695             for (int i = 0; i <= m; i++)
   696                 s.println(prefix + "\tat " + trace[i]);
   697             if (framesInCommon != 0)
   698                 s.println(prefix + "\t... " + framesInCommon + " more");
   699 
   700             // Print suppressed exceptions, if any
   701             for (Throwable se : getSuppressed())
   702                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
   703                                            prefix +"\t", dejaVu);
   704 
   705             // Print cause, if any
   706             Throwable ourCause = getCause();
   707             if (ourCause != null)
   708                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
   709         }
   710     }
   711 
   712     /**
   713      * Prints this throwable and its backtrace to the specified
   714      * print writer.
   715      *
   716      * @param s {@code PrintWriter} to use for output
   717      * @since   JDK1.1
   718      */
   719     public void printStackTrace(PrintWriter s) {
   720         printStackTrace(new WrappedPrintWriter(s));
   721     }
   722 
   723     /**
   724      * Wrapper class for PrintStream and PrintWriter to enable a single
   725      * implementation of printStackTrace.
   726      */
   727     private abstract static class PrintStreamOrWriter {
   728         /** Returns the object to be locked when using this StreamOrWriter */
   729         abstract Object lock();
   730 
   731         /** Prints the specified string as a line on this StreamOrWriter */
   732         abstract void println(Object o);
   733     }
   734 
   735     private static class WrappedPrintStream extends PrintStreamOrWriter {
   736         private final PrintStream printStream;
   737 
   738         WrappedPrintStream(PrintStream printStream) {
   739             this.printStream = printStream;
   740         }
   741 
   742         Object lock() {
   743             return printStream;
   744         }
   745 
   746         void println(Object o) {
   747             printStream.println(o);
   748         }
   749     }
   750 
   751     private static class WrappedPrintWriter extends PrintStreamOrWriter {
   752         private final PrintWriter printWriter;
   753 
   754         WrappedPrintWriter(PrintWriter printWriter) {
   755             this.printWriter = printWriter;
   756         }
   757 
   758         Object lock() {
   759             return printWriter;
   760         }
   761 
   762         void println(Object o) {
   763             printWriter.println(o);
   764         }
   765     }
   766 
   767     /**
   768      * Fills in the execution stack trace. This method records within this
   769      * {@code Throwable} object information about the current state of
   770      * the stack frames for the current thread.
   771      *
   772      * <p>If the stack trace of this {@code Throwable} {@linkplain
   773      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
   774      * writable}, calling this method has no effect.
   775      *
   776      * @return  a reference to this {@code Throwable} instance.
   777      * @see     java.lang.Throwable#printStackTrace()
   778      */
   779     public synchronized Throwable fillInStackTrace() {
   780         if (stackTrace != null ||
   781             backtrace != null /* Out of protocol state */ ) {
   782             fillInStackTrace(0);
   783             stackTrace = UNASSIGNED_STACK;
   784         }
   785         return this;
   786     }
   787 
   788     private native Throwable fillInStackTrace(int dummy);
   789 
   790     /**
   791      * Provides programmatic access to the stack trace information printed by
   792      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
   793      * each representing one stack frame.  The zeroth element of the array
   794      * (assuming the array's length is non-zero) represents the top of the
   795      * stack, which is the last method invocation in the sequence.  Typically,
   796      * this is the point at which this throwable was created and thrown.
   797      * The last element of the array (assuming the array's length is non-zero)
   798      * represents the bottom of the stack, which is the first method invocation
   799      * in the sequence.
   800      *
   801      * <p>Some virtual machines may, under some circumstances, omit one
   802      * or more stack frames from the stack trace.  In the extreme case,
   803      * a virtual machine that has no stack trace information concerning
   804      * this throwable is permitted to return a zero-length array from this
   805      * method.  Generally speaking, the array returned by this method will
   806      * contain one element for every frame that would be printed by
   807      * {@code printStackTrace}.  Writes to the returned array do not
   808      * affect future calls to this method.
   809      *
   810      * @return an array of stack trace elements representing the stack trace
   811      *         pertaining to this throwable.
   812      * @since  1.4
   813      */
   814     public StackTraceElement[] getStackTrace() {
   815         return getOurStackTrace().clone();
   816     }
   817 
   818     private synchronized StackTraceElement[] getOurStackTrace() {
   819         // Initialize stack trace field with information from
   820         // backtrace if this is the first call to this method
   821         if (stackTrace == UNASSIGNED_STACK ||
   822             (stackTrace == null && backtrace != null) /* Out of protocol state */) {
   823             int depth = getStackTraceDepth();
   824             stackTrace = new StackTraceElement[depth];
   825             for (int i=0; i < depth; i++)
   826                 stackTrace[i] = getStackTraceElement(i);
   827         } else if (stackTrace == null) {
   828             return UNASSIGNED_STACK;
   829         }
   830         return stackTrace;
   831     }
   832 
   833     /**
   834      * Sets the stack trace elements that will be returned by
   835      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
   836      * and related methods.
   837      *
   838      * This method, which is designed for use by RPC frameworks and other
   839      * advanced systems, allows the client to override the default
   840      * stack trace that is either generated by {@link #fillInStackTrace()}
   841      * when a throwable is constructed or deserialized when a throwable is
   842      * read from a serialization stream.
   843      *
   844      * <p>If the stack trace of this {@code Throwable} {@linkplain
   845      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
   846      * writable}, calling this method has no effect other than
   847      * validating its argument.
   848      *
   849      * @param   stackTrace the stack trace elements to be associated with
   850      * this {@code Throwable}.  The specified array is copied by this
   851      * call; changes in the specified array after the method invocation
   852      * returns will have no affect on this {@code Throwable}'s stack
   853      * trace.
   854      *
   855      * @throws NullPointerException if {@code stackTrace} is
   856      *         {@code null} or if any of the elements of
   857      *         {@code stackTrace} are {@code null}
   858      *
   859      * @since  1.4
   860      */
   861     public void setStackTrace(StackTraceElement[] stackTrace) {
   862         // Validate argument
   863         StackTraceElement[] defensiveCopy = stackTrace.clone();
   864         for (int i = 0; i < defensiveCopy.length; i++) {
   865             if (defensiveCopy[i] == null)
   866                 throw new NullPointerException("stackTrace[" + i + "]");
   867         }
   868 
   869         synchronized (this) {
   870             if (this.stackTrace == null && // Immutable stack
   871                 backtrace == null) // Test for out of protocol state
   872                 return;
   873             this.stackTrace = defensiveCopy;
   874         }
   875     }
   876 
   877     /**
   878      * Returns the number of elements in the stack trace (or 0 if the stack
   879      * trace is unavailable).
   880      *
   881      * package-protection for use by SharedSecrets.
   882      */
   883     native int getStackTraceDepth();
   884 
   885     /**
   886      * Returns the specified element of the stack trace.
   887      *
   888      * package-protection for use by SharedSecrets.
   889      *
   890      * @param index index of the element to return.
   891      * @throws IndexOutOfBoundsException if {@code index < 0 ||
   892      *         index >= getStackTraceDepth() }
   893      */
   894     native StackTraceElement getStackTraceElement(int index);
   895 
   896     /**
   897      * Reads a {@code Throwable} from a stream, enforcing
   898      * well-formedness constraints on fields.  Null entries and
   899      * self-pointers are not allowed in the list of {@code
   900      * suppressedExceptions}.  Null entries are not allowed for stack
   901      * trace elements.  A null stack trace in the serial form results
   902      * in a zero-length stack element array. A single-element stack
   903      * trace whose entry is equal to {@code new StackTraceElement("",
   904      * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
   905      * stackTrace} field.
   906      *
   907      * Note that there are no constraints on the value the {@code
   908      * cause} field can hold; both {@code null} and {@code this} are
   909      * valid values for the field.
   910      */
   911     private void readObject(ObjectInputStream s)
   912         throws IOException, ClassNotFoundException {
   913         s.defaultReadObject();     // read in all fields
   914         if (suppressedExceptions != null) {
   915             List<Throwable> suppressed = null;
   916             if (suppressedExceptions.isEmpty()) {
   917                 // Use the sentinel for a zero-length list
   918                 suppressed = SUPPRESSED_SENTINEL;
   919             } else { // Copy Throwables to new list
   920                 suppressed = new ArrayList<>(1);
   921                 for (Throwable t : suppressedExceptions) {
   922                     // Enforce constraints on suppressed exceptions in
   923                     // case of corrupt or malicious stream.
   924                     if (t == null)
   925                         throw new NullPointerException(NULL_CAUSE_MESSAGE);
   926                     if (t == this)
   927                         throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
   928                     suppressed.add(t);
   929                 }
   930             }
   931             suppressedExceptions = suppressed;
   932         } // else a null suppressedExceptions field remains null
   933 
   934         /*
   935          * For zero-length stack traces, use a clone of
   936          * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
   937          * allow identity comparison against UNASSIGNED_STACK in
   938          * getOurStackTrace.  The identity of UNASSIGNED_STACK in
   939          * stackTrace indicates to the getOurStackTrace method that
   940          * the stackTrace needs to be constructed from the information
   941          * in backtrace.
   942          */
   943         if (stackTrace != null) {
   944             if (stackTrace.length == 0) {
   945                 stackTrace = UNASSIGNED_STACK.clone();
   946             }  else if (stackTrace.length == 1 &&
   947                         // Check for the marker of an immutable stack trace
   948                         SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) {
   949                 stackTrace = null;
   950             } else { // Verify stack trace elements are non-null.
   951                 for(StackTraceElement ste : stackTrace) {
   952                     if (ste == null)
   953                         throw new NullPointerException("null StackTraceElement in serial stream. ");
   954                 }
   955             }
   956         } else {
   957             // A null stackTrace field in the serial form can result
   958             // from an exception serialized without that field in
   959             // older JDK releases; treat such exceptions as having
   960             // empty stack traces.
   961             stackTrace = UNASSIGNED_STACK.clone();
   962         }
   963     }
   964 
   965     /**
   966      * Write a {@code Throwable} object to a stream.
   967      *
   968      * A {@code null} stack trace field is represented in the serial
   969      * form as a one-element array whose element is equal to {@code
   970      * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
   971      */
   972     private synchronized void writeObject(ObjectOutputStream s)
   973         throws IOException {
   974         // Ensure that the stackTrace field is initialized to a
   975         // non-null value, if appropriate.  As of JDK 7, a null stack
   976         // trace field is a valid value indicating the stack trace
   977         // should not be set.
   978         getOurStackTrace();
   979 
   980         StackTraceElement[] oldStackTrace = stackTrace;
   981         try {
   982             if (stackTrace == null)
   983                 stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
   984             s.defaultWriteObject();
   985         } finally {
   986             stackTrace = oldStackTrace;
   987         }
   988     }
   989 
   990     /**
   991      * Appends the specified exception to the exceptions that were
   992      * suppressed in order to deliver this exception. This method is
   993      * thread-safe and typically called (automatically and implicitly)
   994      * by the {@code try}-with-resources statement.
   995      *
   996      * <p>The suppression behavior is enabled <em>unless</em> disabled
   997      * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
   998      * a constructor}.  When suppression is disabled, this method does
   999      * nothing other than to validate its argument.
  1000      *
  1001      * <p>Note that when one exception {@linkplain
  1002      * #initCause(Throwable) causes} another exception, the first
  1003      * exception is usually caught and then the second exception is
  1004      * thrown in response.  In other words, there is a causal
  1005      * connection between the two exceptions.
  1006      *
  1007      * In contrast, there are situations where two independent
  1008      * exceptions can be thrown in sibling code blocks, in particular
  1009      * in the {@code try} block of a {@code try}-with-resources
  1010      * statement and the compiler-generated {@code finally} block
  1011      * which closes the resource.
  1012      *
  1013      * In these situations, only one of the thrown exceptions can be
  1014      * propagated.  In the {@code try}-with-resources statement, when
  1015      * there are two such exceptions, the exception originating from
  1016      * the {@code try} block is propagated and the exception from the
  1017      * {@code finally} block is added to the list of exceptions
  1018      * suppressed by the exception from the {@code try} block.  As an
  1019      * exception unwinds the stack, it can accumulate multiple
  1020      * suppressed exceptions.
  1021      *
  1022      * <p>An exception may have suppressed exceptions while also being
  1023      * caused by another exception.  Whether or not an exception has a
  1024      * cause is semantically known at the time of its creation, unlike
  1025      * whether or not an exception will suppress other exceptions
  1026      * which is typically only determined after an exception is
  1027      * thrown.
  1028      *
  1029      * <p>Note that programmer written code is also able to take
  1030      * advantage of calling this method in situations where there are
  1031      * multiple sibling exceptions and only one can be propagated.
  1032      *
  1033      * @param exception the exception to be added to the list of
  1034      *        suppressed exceptions
  1035      * @throws IllegalArgumentException if {@code exception} is this
  1036      *         throwable; a throwable cannot suppress itself.
  1037      * @throws NullPointerException if {@code exception} is {@code null}
  1038      * @since 1.7
  1039      */
  1040     public final synchronized void addSuppressed(Throwable exception) {
  1041         if (exception == this)
  1042             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
  1043 
  1044         if (exception == null)
  1045             throw new NullPointerException(NULL_CAUSE_MESSAGE);
  1046 
  1047         if (suppressedExceptions == null) // Suppressed exceptions not recorded
  1048             return;
  1049 
  1050         if (suppressedExceptions == SUPPRESSED_SENTINEL)
  1051             suppressedExceptions = new ArrayList<>(1);
  1052 
  1053         suppressedExceptions.add(exception);
  1054     }
  1055 
  1056     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
  1057 
  1058     /**
  1059      * Returns an array containing all of the exceptions that were
  1060      * suppressed, typically by the {@code try}-with-resources
  1061      * statement, in order to deliver this exception.
  1062      *
  1063      * If no exceptions were suppressed or {@linkplain
  1064      * #Throwable(String, Throwable, boolean, boolean) suppression is
  1065      * disabled}, an empty array is returned.  This method is
  1066      * thread-safe.  Writes to the returned array do not affect future
  1067      * calls to this method.
  1068      *
  1069      * @return an array containing all of the exceptions that were
  1070      *         suppressed to deliver this exception.
  1071      * @since 1.7
  1072      */
  1073     public final synchronized Throwable[] getSuppressed() {
  1074         if (suppressedExceptions == SUPPRESSED_SENTINEL ||
  1075             suppressedExceptions == null)
  1076             return EMPTY_THROWABLE_ARRAY;
  1077         else
  1078             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
  1079     }
  1080 }