emul/src/main/java/java/lang/Throwable.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 29 Sep 2012 10:47:42 +0200
branchemul
changeset 65 f99a92839285
parent 61 4b334950499d
child 83 89b2cb4068fc
permissions -rw-r--r--
Commenting out methods that should not be implemented in JavaScript version
     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 
    29 /**
    30  * The {@code Throwable} class is the superclass of all errors and
    31  * exceptions in the Java language. Only objects that are instances of this
    32  * class (or one of its subclasses) are thrown by the Java Virtual Machine or
    33  * can be thrown by the Java {@code throw} statement. Similarly, only
    34  * this class or one of its subclasses can be the argument type in a
    35  * {@code catch} clause.
    36  *
    37  * For the purposes of compile-time checking of exceptions, {@code
    38  * Throwable} and any subclass of {@code Throwable} that is not also a
    39  * subclass of either {@link RuntimeException} or {@link Error} are
    40  * regarded as checked exceptions.
    41  *
    42  * <p>Instances of two subclasses, {@link java.lang.Error} and
    43  * {@link java.lang.Exception}, are conventionally used to indicate
    44  * that exceptional situations have occurred. Typically, these instances
    45  * are freshly created in the context of the exceptional situation so
    46  * as to include relevant information (such as stack trace data).
    47  *
    48  * <p>A throwable contains a snapshot of the execution stack of its
    49  * thread at the time it was created. It can also contain a message
    50  * string that gives more information about the error. Over time, a
    51  * throwable can {@linkplain Throwable#addSuppressed suppress} other
    52  * throwables from being propagated.  Finally, the throwable can also
    53  * contain a <i>cause</i>: another throwable that caused this
    54  * throwable to be constructed.  The recording of this causal information
    55  * is referred to as the <i>chained exception</i> facility, as the
    56  * cause can, itself, have a cause, and so on, leading to a "chain" of
    57  * exceptions, each caused by another.
    58  *
    59  * <p>One reason that a throwable may have a cause is that the class that
    60  * throws it is built atop a lower layered abstraction, and an operation on
    61  * the upper layer fails due to a failure in the lower layer.  It would be bad
    62  * design to let the throwable thrown by the lower layer propagate outward, as
    63  * it is generally unrelated to the abstraction provided by the upper layer.
    64  * Further, doing so would tie the API of the upper layer to the details of
    65  * its implementation, assuming the lower layer's exception was a checked
    66  * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
    67  * cause) allows the upper layer to communicate the details of the failure to
    68  * its caller without incurring either of these shortcomings.  It preserves
    69  * the flexibility to change the implementation of the upper layer without
    70  * changing its API (in particular, the set of exceptions thrown by its
    71  * methods).
    72  *
    73  * <p>A second reason that a throwable may have a cause is that the method
    74  * that throws it must conform to a general-purpose interface that does not
    75  * permit the method to throw the cause directly.  For example, suppose
    76  * a persistent collection conforms to the {@link java.util.Collection
    77  * Collection} interface, and that its persistence is implemented atop
    78  * {@code java.io}.  Suppose the internals of the {@code add} method
    79  * can throw an {@link java.io.IOException IOException}.  The implementation
    80  * can communicate the details of the {@code IOException} to its caller
    81  * while conforming to the {@code Collection} interface by wrapping the
    82  * {@code IOException} in an appropriate unchecked exception.  (The
    83  * specification for the persistent collection should indicate that it is
    84  * capable of throwing such exceptions.)
    85  *
    86  * <p>A cause can be associated with a throwable in two ways: via a
    87  * constructor that takes the cause as an argument, or via the
    88  * {@link #initCause(Throwable)} method.  New throwable classes that
    89  * wish to allow causes to be associated with them should provide constructors
    90  * that take a cause and delegate (perhaps indirectly) to one of the
    91  * {@code Throwable} constructors that takes a cause.
    92  *
    93  * Because the {@code initCause} method is public, it allows a cause to be
    94  * associated with any throwable, even a "legacy throwable" whose
    95  * implementation predates the addition of the exception chaining mechanism to
    96  * {@code Throwable}.
    97  *
    98  * <p>By convention, class {@code Throwable} and its subclasses have two
    99  * constructors, one that takes no arguments and one that takes a
   100  * {@code String} argument that can be used to produce a detail message.
   101  * Further, those subclasses that might likely have a cause associated with
   102  * them should have two more constructors, one that takes a
   103  * {@code Throwable} (the cause), and one that takes a
   104  * {@code String} (the detail message) and a {@code Throwable} (the
   105  * cause).
   106  *
   107  * @author  unascribed
   108  * @author  Josh Bloch (Added exception chaining and programmatic access to
   109  *          stack trace in 1.4.)
   110  * @jls 11.2 Compile-Time Checking of Exceptions
   111  * @since JDK1.0
   112  */
   113 public class Throwable implements Serializable {
   114     /** use serialVersionUID from JDK 1.0.2 for interoperability */
   115     private static final long serialVersionUID = -3042686055658047285L;
   116 
   117     /**
   118      * Native code saves some indication of the stack backtrace in this slot.
   119      */
   120     private transient Object backtrace;
   121 
   122     /**
   123      * Specific details about the Throwable.  For example, for
   124      * {@code FileNotFoundException}, this contains the name of
   125      * the file that could not be found.
   126      *
   127      * @serial
   128      */
   129     private String detailMessage;
   130 
   131 
   132     /**
   133      * Holder class to defer initializing sentinel objects only used
   134      * for serialization.
   135      */
   136     private static class SentinelHolder {
   137         /**
   138          * {@linkplain #setStackTrace(StackTraceElement[]) Setting the
   139          * stack trace} to a one-element array containing this sentinel
   140          * value indicates future attempts to set the stack trace will be
   141          * ignored.  The sentinal is equal to the result of calling:<br>
   142          * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
   143          */
   144         public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
   145             new StackTraceElement("", "", null, Integer.MIN_VALUE);
   146 
   147         /**
   148          * Sentinel value used in the serial form to indicate an immutable
   149          * stack trace.
   150          */
   151         public static final StackTraceElement[] STACK_TRACE_SENTINEL =
   152             new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
   153     }
   154 
   155     /**
   156      * A shared value for an empty stack.
   157      */
   158     private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];
   159 
   160     /*
   161      * To allow Throwable objects to be made immutable and safely
   162      * reused by the JVM, such as OutOfMemoryErrors, fields of
   163      * Throwable that are writable in response to user actions, cause,
   164      * stackTrace, and suppressedExceptions obey the following
   165      * protocol:
   166      *
   167      * 1) The fields are initialized to a non-null sentinel value
   168      * which indicates the value has logically not been set.
   169      *
   170      * 2) Writing a null to the field indicates further writes
   171      * are forbidden
   172      *
   173      * 3) The sentinel value may be replaced with another non-null
   174      * value.
   175      *
   176      * For example, implementations of the HotSpot JVM have
   177      * preallocated OutOfMemoryError objects to provide for better
   178      * diagnosability of that situation.  These objects are created
   179      * without calling the constructor for that class and the fields
   180      * in question are initialized to null.  To support this
   181      * capability, any new fields added to Throwable that require
   182      * being initialized to a non-null value require a coordinated JVM
   183      * change.
   184      */
   185 
   186     /**
   187      * The throwable that caused this throwable to get thrown, or null if this
   188      * throwable was not caused by another throwable, or if the causative
   189      * throwable is unknown.  If this field is equal to this throwable itself,
   190      * it indicates that the cause of this throwable has not yet been
   191      * initialized.
   192      *
   193      * @serial
   194      * @since 1.4
   195      */
   196     private Throwable cause = this;
   197 
   198     /**
   199      * The stack trace, as returned by {@link #getStackTrace()}.
   200      *
   201      * The field is initialized to a zero-length array.  A {@code
   202      * null} value of this field indicates subsequent calls to {@link
   203      * #setStackTrace(StackTraceElement[])} and {@link
   204      * #fillInStackTrace()} will be be no-ops.
   205      *
   206      * @serial
   207      * @since 1.4
   208      */
   209     private StackTraceElement[] stackTrace = UNASSIGNED_STACK;
   210 
   211     // Setting this static field introduces an acceptable
   212     // initialization dependency on a few java.util classes.
   213 // I don't think this dependency is acceptable
   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                                          Object dejaVu) {
   679         assert Thread.holdsLock(s.lock());
   680         {
   681             // Compute number of frames in common between this and enclosing trace
   682             StackTraceElement[] trace = getOurStackTrace();
   683             int m = trace.length - 1;
   684             int n = enclosingTrace.length - 1;
   685             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
   686                 m--; n--;
   687             }
   688             int framesInCommon = trace.length - 1 - m;
   689 
   690             // Print our stack trace
   691             s.println(prefix + caption + this);
   692             for (int i = 0; i <= m; i++)
   693                 s.println(prefix + "\tat " + trace[i]);
   694             if (framesInCommon != 0)
   695                 s.println(prefix + "\t... " + framesInCommon + " more");
   696 
   697             // Print suppressed exceptions, if any
   698             for (Throwable se : getSuppressed())
   699                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
   700                                            prefix +"\t", dejaVu);
   701 
   702             // Print cause, if any
   703             Throwable ourCause = getCause();
   704             if (ourCause != null)
   705                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
   706         }
   707     }
   708 
   709     /**
   710      * Prints this throwable and its backtrace to the specified
   711      * print writer.
   712      *
   713      * @param s {@code PrintWriter} to use for output
   714      * @since   JDK1.1
   715      */
   716     public void printStackTrace(PrintWriter s) {
   717         printStackTrace(new WrappedPrintWriter(s));
   718     }
   719 
   720     /**
   721      * Wrapper class for PrintStream and PrintWriter to enable a single
   722      * implementation of printStackTrace.
   723      */
   724     private abstract static class PrintStreamOrWriter {
   725         /** Returns the object to be locked when using this StreamOrWriter */
   726         abstract Object lock();
   727 
   728         /** Prints the specified string as a line on this StreamOrWriter */
   729         abstract void println(Object o);
   730     }
   731 
   732     private static class WrappedPrintStream extends PrintStreamOrWriter {
   733         private final PrintStream printStream;
   734 
   735         WrappedPrintStream(PrintStream printStream) {
   736             this.printStream = printStream;
   737         }
   738 
   739         Object lock() {
   740             return printStream;
   741         }
   742 
   743         void println(Object o) {
   744             printStream.println(o);
   745         }
   746     }
   747 
   748     private static class WrappedPrintWriter extends PrintStreamOrWriter {
   749         private final PrintWriter printWriter;
   750 
   751         WrappedPrintWriter(PrintWriter printWriter) {
   752             this.printWriter = printWriter;
   753         }
   754 
   755         Object lock() {
   756             return printWriter;
   757         }
   758 
   759         void println(Object o) {
   760             printWriter.println(o);
   761         }
   762     }
   763 
   764     /**
   765      * Fills in the execution stack trace. This method records within this
   766      * {@code Throwable} object information about the current state of
   767      * the stack frames for the current thread.
   768      *
   769      * <p>If the stack trace of this {@code Throwable} {@linkplain
   770      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
   771      * writable}, calling this method has no effect.
   772      *
   773      * @return  a reference to this {@code Throwable} instance.
   774      * @see     java.lang.Throwable#printStackTrace()
   775      */
   776     public synchronized Throwable fillInStackTrace() {
   777         if (stackTrace != null ||
   778             backtrace != null /* Out of protocol state */ ) {
   779             fillInStackTrace(0);
   780             stackTrace = UNASSIGNED_STACK;
   781         }
   782         return this;
   783     }
   784 
   785     private native Throwable fillInStackTrace(int dummy);
   786 
   787     /**
   788      * Provides programmatic access to the stack trace information printed by
   789      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
   790      * each representing one stack frame.  The zeroth element of the array
   791      * (assuming the array's length is non-zero) represents the top of the
   792      * stack, which is the last method invocation in the sequence.  Typically,
   793      * this is the point at which this throwable was created and thrown.
   794      * The last element of the array (assuming the array's length is non-zero)
   795      * represents the bottom of the stack, which is the first method invocation
   796      * in the sequence.
   797      *
   798      * <p>Some virtual machines may, under some circumstances, omit one
   799      * or more stack frames from the stack trace.  In the extreme case,
   800      * a virtual machine that has no stack trace information concerning
   801      * this throwable is permitted to return a zero-length array from this
   802      * method.  Generally speaking, the array returned by this method will
   803      * contain one element for every frame that would be printed by
   804      * {@code printStackTrace}.  Writes to the returned array do not
   805      * affect future calls to this method.
   806      *
   807      * @return an array of stack trace elements representing the stack trace
   808      *         pertaining to this throwable.
   809      * @since  1.4
   810      */
   811     public StackTraceElement[] getStackTrace() {
   812         return getOurStackTrace().clone();
   813     }
   814 
   815     private synchronized StackTraceElement[] getOurStackTrace() {
   816         // Initialize stack trace field with information from
   817         // backtrace if this is the first call to this method
   818         if (stackTrace == UNASSIGNED_STACK ||
   819             (stackTrace == null && backtrace != null) /* Out of protocol state */) {
   820             int depth = getStackTraceDepth();
   821             stackTrace = new StackTraceElement[depth];
   822             for (int i=0; i < depth; i++)
   823                 stackTrace[i] = getStackTraceElement(i);
   824         } else if (stackTrace == null) {
   825             return UNASSIGNED_STACK;
   826         }
   827         return stackTrace;
   828     }
   829 
   830     /**
   831      * Sets the stack trace elements that will be returned by
   832      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
   833      * and related methods.
   834      *
   835      * This method, which is designed for use by RPC frameworks and other
   836      * advanced systems, allows the client to override the default
   837      * stack trace that is either generated by {@link #fillInStackTrace()}
   838      * when a throwable is constructed or deserialized when a throwable is
   839      * read from a serialization stream.
   840      *
   841      * <p>If the stack trace of this {@code Throwable} {@linkplain
   842      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
   843      * writable}, calling this method has no effect other than
   844      * validating its argument.
   845      *
   846      * @param   stackTrace the stack trace elements to be associated with
   847      * this {@code Throwable}.  The specified array is copied by this
   848      * call; changes in the specified array after the method invocation
   849      * returns will have no affect on this {@code Throwable}'s stack
   850      * trace.
   851      *
   852      * @throws NullPointerException if {@code stackTrace} is
   853      *         {@code null} or if any of the elements of
   854      *         {@code stackTrace} are {@code null}
   855      *
   856      * @since  1.4
   857      */
   858     public void setStackTrace(StackTraceElement[] stackTrace) {
   859         // Validate argument
   860         StackTraceElement[] defensiveCopy = stackTrace.clone();
   861         for (int i = 0; i < defensiveCopy.length; i++) {
   862             if (defensiveCopy[i] == null)
   863                 throw new NullPointerException("stackTrace[" + i + "]");
   864         }
   865 
   866         synchronized (this) {
   867             if (this.stackTrace == null && // Immutable stack
   868                 backtrace == null) // Test for out of protocol state
   869                 return;
   870             this.stackTrace = defensiveCopy;
   871         }
   872     }
   873 
   874     /**
   875      * Returns the number of elements in the stack trace (or 0 if the stack
   876      * trace is unavailable).
   877      *
   878      * package-protection for use by SharedSecrets.
   879      */
   880     native int getStackTraceDepth();
   881 
   882     /**
   883      * Returns the specified element of the stack trace.
   884      *
   885      * package-protection for use by SharedSecrets.
   886      *
   887      * @param index index of the element to return.
   888      * @throws IndexOutOfBoundsException if {@code index < 0 ||
   889      *         index >= getStackTraceDepth() }
   890      */
   891     native StackTraceElement getStackTraceElement(int index);
   892 
   893     /**
   894      * Reads a {@code Throwable} from a stream, enforcing
   895      * well-formedness constraints on fields.  Null entries and
   896      * self-pointers are not allowed in the list of {@code
   897      * suppressedExceptions}.  Null entries are not allowed for stack
   898      * trace elements.  A null stack trace in the serial form results
   899      * in a zero-length stack element array. A single-element stack
   900      * trace whose entry is equal to {@code new StackTraceElement("",
   901      * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
   902      * stackTrace} field.
   903      *
   904      * Note that there are no constraints on the value the {@code
   905      * cause} field can hold; both {@code null} and {@code this} are
   906      * valid values for the field.
   907      */
   908 //    private void readObject(ObjectInputStream s)
   909 //        throws IOException, ClassNotFoundException {
   910 //        s.defaultReadObject();     // read in all fields
   911 //        if (suppressedExceptions != null) {
   912 //            List<Throwable> suppressed = null;
   913 //            if (suppressedExceptions.isEmpty()) {
   914 //                // Use the sentinel for a zero-length list
   915 //                suppressed = SUPPRESSED_SENTINEL;
   916 //            } else { // Copy Throwables to new list
   917 //                suppressed = new ArrayList<Throwable>(1);
   918 //                for (Throwable t : suppressedExceptions) {
   919 //                    // Enforce constraints on suppressed exceptions in
   920 //                    // case of corrupt or malicious stream.
   921 //                    if (t == null)
   922 //                        throw new NullPointerException(NULL_CAUSE_MESSAGE);
   923 //                    if (t == this)
   924 //                        throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
   925 //                    suppressed.add(t);
   926 //                }
   927 //            }
   928 //            suppressedExceptions = suppressed;
   929 //        } // else a null suppressedExceptions field remains null
   930 //
   931 //        /*
   932 //         * For zero-length stack traces, use a clone of
   933 //         * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
   934 //         * allow identity comparison against UNASSIGNED_STACK in
   935 //         * getOurStackTrace.  The identity of UNASSIGNED_STACK in
   936 //         * stackTrace indicates to the getOurStackTrace method that
   937 //         * the stackTrace needs to be constructed from the information
   938 //         * in backtrace.
   939 //         */
   940 //        if (stackTrace != null) {
   941 //            if (stackTrace.length == 0) {
   942 //                stackTrace = UNASSIGNED_STACK.clone();
   943 //            }  else if (stackTrace.length == 1 &&
   944 //                        // Check for the marker of an immutable stack trace
   945 //                        SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) {
   946 //                stackTrace = null;
   947 //            } else { // Verify stack trace elements are non-null.
   948 //                for(StackTraceElement ste : stackTrace) {
   949 //                    if (ste == null)
   950 //                        throw new NullPointerException("null StackTraceElement in serial stream. ");
   951 //                }
   952 //            }
   953 //        } else {
   954 //            // A null stackTrace field in the serial form can result
   955 //            // from an exception serialized without that field in
   956 //            // older JDK releases; treat such exceptions as having
   957 //            // empty stack traces.
   958 //            stackTrace = UNASSIGNED_STACK.clone();
   959 //        }
   960 //    }
   961 
   962     /**
   963      * Write a {@code Throwable} object to a stream.
   964      *
   965      * A {@code null} stack trace field is represented in the serial
   966      * form as a one-element array whose element is equal to {@code
   967      * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
   968      */
   969     private synchronized void writeObject(ObjectOutputStream s)
   970         throws IOException {
   971         // Ensure that the stackTrace field is initialized to a
   972         // non-null value, if appropriate.  As of JDK 7, a null stack
   973         // trace field is a valid value indicating the stack trace
   974         // should not be set.
   975         getOurStackTrace();
   976 
   977         StackTraceElement[] oldStackTrace = stackTrace;
   978         try {
   979             if (stackTrace == null)
   980                 stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
   981             s.defaultWriteObject();
   982         } finally {
   983             stackTrace = oldStackTrace;
   984         }
   985     }
   986 
   987     /**
   988      * Appends the specified exception to the exceptions that were
   989      * suppressed in order to deliver this exception. This method is
   990      * thread-safe and typically called (automatically and implicitly)
   991      * by the {@code try}-with-resources statement.
   992      *
   993      * <p>The suppression behavior is enabled <em>unless</em> disabled
   994      * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
   995      * a constructor}.  When suppression is disabled, this method does
   996      * nothing other than to validate its argument.
   997      *
   998      * <p>Note that when one exception {@linkplain
   999      * #initCause(Throwable) causes} another exception, the first
  1000      * exception is usually caught and then the second exception is
  1001      * thrown in response.  In other words, there is a causal
  1002      * connection between the two exceptions.
  1003      *
  1004      * In contrast, there are situations where two independent
  1005      * exceptions can be thrown in sibling code blocks, in particular
  1006      * in the {@code try} block of a {@code try}-with-resources
  1007      * statement and the compiler-generated {@code finally} block
  1008      * which closes the resource.
  1009      *
  1010      * In these situations, only one of the thrown exceptions can be
  1011      * propagated.  In the {@code try}-with-resources statement, when
  1012      * there are two such exceptions, the exception originating from
  1013      * the {@code try} block is propagated and the exception from the
  1014      * {@code finally} block is added to the list of exceptions
  1015      * suppressed by the exception from the {@code try} block.  As an
  1016      * exception unwinds the stack, it can accumulate multiple
  1017      * suppressed exceptions.
  1018      *
  1019      * <p>An exception may have suppressed exceptions while also being
  1020      * caused by another exception.  Whether or not an exception has a
  1021      * cause is semantically known at the time of its creation, unlike
  1022      * whether or not an exception will suppress other exceptions
  1023      * which is typically only determined after an exception is
  1024      * thrown.
  1025      *
  1026      * <p>Note that programmer written code is also able to take
  1027      * advantage of calling this method in situations where there are
  1028      * multiple sibling exceptions and only one can be propagated.
  1029      *
  1030      * @param exception the exception to be added to the list of
  1031      *        suppressed exceptions
  1032      * @throws IllegalArgumentException if {@code exception} is this
  1033      *         throwable; a throwable cannot suppress itself.
  1034      * @throws NullPointerException if {@code exception} is {@code null}
  1035      * @since 1.7
  1036      */
  1037     public final synchronized void addSuppressed(Throwable exception) {
  1038         if (exception == this)
  1039             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
  1040 
  1041         if (exception == null)
  1042             throw new NullPointerException(NULL_CAUSE_MESSAGE);
  1043 
  1044 //        if (suppressedExceptions == null) // Suppressed exceptions not recorded
  1045 //            return;
  1046 //
  1047 //        if (suppressedExceptions == SUPPRESSED_SENTINEL)
  1048 //            suppressedExceptions = new ArrayList<Throwable>(1);
  1049 //
  1050 //        suppressedExceptions.add(exception);
  1051     }
  1052 
  1053     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
  1054 
  1055     /**
  1056      * Returns an array containing all of the exceptions that were
  1057      * suppressed, typically by the {@code try}-with-resources
  1058      * statement, in order to deliver this exception.
  1059      *
  1060      * If no exceptions were suppressed or {@linkplain
  1061      * #Throwable(String, Throwable, boolean, boolean) suppression is
  1062      * disabled}, an empty array is returned.  This method is
  1063      * thread-safe.  Writes to the returned array do not affect future
  1064      * calls to this method.
  1065      *
  1066      * @return an array containing all of the exceptions that were
  1067      *         suppressed to deliver this exception.
  1068      * @since 1.7
  1069      */
  1070     public final synchronized Throwable[] getSuppressed() {
  1071         return new Throwable[0];
  1072 //        if (suppressedExceptions == SUPPRESSED_SENTINEL ||
  1073 //            suppressedExceptions == null)
  1074 //            return EMPTY_THROWABLE_ARRAY;
  1075 //        else
  1076 //            return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
  1077     }
  1078 }