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