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.
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.
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).
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.
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
28 import org.apidesign.bck2brwsr.core.JavaScriptBody;
31 * The {@code Throwable} class is the superclass of all errors and
32 * exceptions in the Java language. Only objects that are instances of this
33 * class (or one of its subclasses) are thrown by the Java Virtual Machine or
34 * can be thrown by the Java {@code throw} statement. Similarly, only
35 * this class or one of its subclasses can be the argument type in a
36 * {@code catch} clause.
38 * For the purposes of compile-time checking of exceptions, {@code
39 * Throwable} and any subclass of {@code Throwable} that is not also a
40 * subclass of either {@link RuntimeException} or {@link Error} are
41 * regarded as checked exceptions.
43 * <p>Instances of two subclasses, {@link java.lang.Error} and
44 * {@link java.lang.Exception}, are conventionally used to indicate
45 * that exceptional situations have occurred. Typically, these instances
46 * are freshly created in the context of the exceptional situation so
47 * as to include relevant information (such as stack trace data).
49 * <p>A throwable contains a snapshot of the execution stack of its
50 * thread at the time it was created. It can also contain a message
51 * string that gives more information about the error. Over time, a
52 * throwable can {@linkplain Throwable#addSuppressed suppress} other
53 * throwables from being propagated. Finally, the throwable can also
54 * contain a <i>cause</i>: another throwable that caused this
55 * throwable to be constructed. The recording of this causal information
56 * is referred to as the <i>chained exception</i> facility, as the
57 * cause can, itself, have a cause, and so on, leading to a "chain" of
58 * exceptions, each caused by another.
60 * <p>One reason that a throwable may have a cause is that the class that
61 * throws it is built atop a lower layered abstraction, and an operation on
62 * the upper layer fails due to a failure in the lower layer. It would be bad
63 * design to let the throwable thrown by the lower layer propagate outward, as
64 * it is generally unrelated to the abstraction provided by the upper layer.
65 * Further, doing so would tie the API of the upper layer to the details of
66 * its implementation, assuming the lower layer's exception was a checked
67 * exception. Throwing a "wrapped exception" (i.e., an exception containing a
68 * cause) allows the upper layer to communicate the details of the failure to
69 * its caller without incurring either of these shortcomings. It preserves
70 * the flexibility to change the implementation of the upper layer without
71 * changing its API (in particular, the set of exceptions thrown by its
74 * <p>A second reason that a throwable may have a cause is that the method
75 * that throws it must conform to a general-purpose interface that does not
76 * permit the method to throw the cause directly. For example, suppose
77 * a persistent collection conforms to the {@link java.util.Collection
78 * Collection} interface, and that its persistence is implemented atop
79 * {@code java.io}. Suppose the internals of the {@code add} method
80 * can throw an {@link java.io.IOException IOException}. The implementation
81 * can communicate the details of the {@code IOException} to its caller
82 * while conforming to the {@code Collection} interface by wrapping the
83 * {@code IOException} in an appropriate unchecked exception. (The
84 * specification for the persistent collection should indicate that it is
85 * capable of throwing such exceptions.)
87 * <p>A cause can be associated with a throwable in two ways: via a
88 * constructor that takes the cause as an argument, or via the
89 * {@link #initCause(Throwable)} method. New throwable classes that
90 * wish to allow causes to be associated with them should provide constructors
91 * that take a cause and delegate (perhaps indirectly) to one of the
92 * {@code Throwable} constructors that takes a cause.
94 * Because the {@code initCause} method is public, it allows a cause to be
95 * associated with any throwable, even a "legacy throwable" whose
96 * implementation predates the addition of the exception chaining mechanism to
99 * <p>By convention, class {@code Throwable} and its subclasses have two
100 * constructors, one that takes no arguments and one that takes a
101 * {@code String} argument that can be used to produce a detail message.
102 * Further, those subclasses that might likely have a cause associated with
103 * them should have two more constructors, one that takes a
104 * {@code Throwable} (the cause), and one that takes a
105 * {@code String} (the detail message) and a {@code Throwable} (the
109 * @author Josh Bloch (Added exception chaining and programmatic access to
110 * stack trace in 1.4.)
111 * @jls 11.2 Compile-Time Checking of Exceptions
114 public class Throwable implements Serializable {
115 /** use serialVersionUID from JDK 1.0.2 for interoperability */
116 private static final long serialVersionUID = -3042686055658047285L;
119 * Native code saves some indication of the stack backtrace in this slot.
121 private transient Object backtrace;
124 * Specific details about the Throwable. For example, for
125 * {@code FileNotFoundException}, this contains the name of
126 * the file that could not be found.
130 private String detailMessage;
134 * Holder class to defer initializing sentinel objects only used
137 private static class SentinelHolder {
139 * {@linkplain #setStackTrace(StackTraceElement[]) Setting the
140 * stack trace} to a one-element array containing this sentinel
141 * value indicates future attempts to set the stack trace will be
142 * ignored. The sentinal is equal to the result of calling:<br>
143 * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
145 public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
146 new StackTraceElement("", "", null, Integer.MIN_VALUE);
149 * Sentinel value used in the serial form to indicate an immutable
152 public static final StackTraceElement[] STACK_TRACE_SENTINEL =
153 new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
157 * A shared value for an empty stack.
159 private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];
162 * To allow Throwable objects to be made immutable and safely
163 * reused by the JVM, such as OutOfMemoryErrors, fields of
164 * Throwable that are writable in response to user actions, cause,
165 * stackTrace, and suppressedExceptions obey the following
168 * 1) The fields are initialized to a non-null sentinel value
169 * which indicates the value has logically not been set.
171 * 2) Writing a null to the field indicates further writes
174 * 3) The sentinel value may be replaced with another non-null
177 * For example, implementations of the HotSpot JVM have
178 * preallocated OutOfMemoryError objects to provide for better
179 * diagnosability of that situation. These objects are created
180 * without calling the constructor for that class and the fields
181 * in question are initialized to null. To support this
182 * capability, any new fields added to Throwable that require
183 * being initialized to a non-null value require a coordinated JVM
188 * The throwable that caused this throwable to get thrown, or null if this
189 * throwable was not caused by another throwable, or if the causative
190 * throwable is unknown. If this field is equal to this throwable itself,
191 * it indicates that the cause of this throwable has not yet been
197 private Throwable cause = this;
200 * The stack trace, as returned by {@link #getStackTrace()}.
202 * The field is initialized to a zero-length array. A {@code
203 * null} value of this field indicates subsequent calls to {@link
204 * #setStackTrace(StackTraceElement[])} and {@link
205 * #fillInStackTrace()} will be be no-ops.
210 private StackTraceElement[] stackTrace = UNASSIGNED_STACK;
212 // Setting this static field introduces an acceptable
213 // initialization dependency on a few java.util classes.
214 // I don't think this dependency is acceptable
215 // private static final List<Throwable> SUPPRESSED_SENTINEL =
216 // Collections.unmodifiableList(new ArrayList<Throwable>(0));
219 * The list of suppressed exceptions, as returned by {@link
220 * #getSuppressed()}. The list is initialized to a zero-element
221 * unmodifiable sentinel list. When a serialized Throwable is
222 * read in, if the {@code suppressedExceptions} field points to a
223 * zero-element list, the field is reset to the sentinel value.
228 // private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
230 /** Message for trying to suppress a null exception. */
231 private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
233 /** Message for trying to suppress oneself. */
234 private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
236 /** Caption for labeling causative exception stack traces */
237 private static final String CAUSE_CAPTION = "Caused by: ";
239 /** Caption for labeling suppressed exception stack traces */
240 private static final String SUPPRESSED_CAPTION = "Suppressed: ";
243 * Constructs a new throwable with {@code null} as its detail message.
244 * The cause is not initialized, and may subsequently be initialized by a
245 * call to {@link #initCause}.
247 * <p>The {@link #fillInStackTrace()} method is called to initialize
248 * the stack trace data in the newly created throwable.
255 * Constructs a new throwable with the specified detail message. The
256 * cause is not initialized, and may subsequently be initialized by
257 * a call to {@link #initCause}.
259 * <p>The {@link #fillInStackTrace()} method is called to initialize
260 * the stack trace data in the newly created throwable.
262 * @param message the detail message. The detail message is saved for
263 * later retrieval by the {@link #getMessage()} method.
265 public Throwable(String message) {
267 detailMessage = message;
271 * Constructs a new throwable with the specified detail message and
272 * cause. <p>Note that the detail message associated with
273 * {@code cause} is <i>not</i> automatically incorporated in
274 * this throwable's detail message.
276 * <p>The {@link #fillInStackTrace()} method is called to initialize
277 * the stack trace data in the newly created throwable.
279 * @param message the detail message (which is saved for later retrieval
280 * by the {@link #getMessage()} method).
281 * @param cause the cause (which is saved for later retrieval by the
282 * {@link #getCause()} method). (A {@code null} value is
283 * permitted, and indicates that the cause is nonexistent or
287 public Throwable(String message, Throwable cause) {
289 detailMessage = message;
294 * Constructs a new throwable with the specified cause and a detail
295 * message of {@code (cause==null ? null : cause.toString())} (which
296 * typically contains the class and detail message of {@code cause}).
297 * This constructor is useful for throwables that are little more than
298 * wrappers for other throwables (for example, {@link
299 * java.security.PrivilegedActionException}).
301 * <p>The {@link #fillInStackTrace()} method is called to initialize
302 * the stack trace data in the newly created throwable.
304 * @param cause the cause (which is saved for later retrieval by the
305 * {@link #getCause()} method). (A {@code null} value is
306 * permitted, and indicates that the cause is nonexistent or
310 public Throwable(Throwable cause) {
312 detailMessage = (cause==null ? null : cause.toString());
317 * Constructs a new throwable with the specified detail message,
318 * cause, {@linkplain #addSuppressed suppression} enabled or
319 * disabled, and writable stack trace enabled or disabled. If
320 * suppression is disabled, {@link #getSuppressed} for this object
321 * will return a zero-length array and calls to {@link
322 * #addSuppressed} that would otherwise append an exception to the
323 * suppressed list will have no effect. If the writable stack
324 * trace is false, this constructor will not call {@link
325 * #fillInStackTrace()}, a {@code null} will be written to the
326 * {@code stackTrace} field, and subsequent calls to {@code
327 * fillInStackTrace} and {@link
328 * #setStackTrace(StackTraceElement[])} will not set the stack
329 * trace. If the writable stack trace is false, {@link
330 * #getStackTrace} will return a zero length array.
332 * <p>Note that the other constructors of {@code Throwable} treat
333 * suppression as being enabled and the stack trace as being
334 * writable. Subclasses of {@code Throwable} should document any
335 * conditions under which suppression is disabled and document
336 * conditions under which the stack trace is not writable.
337 * Disabling of suppression should only occur in exceptional
338 * circumstances where special requirements exist, such as a
339 * virtual machine reusing exception objects under low-memory
340 * situations. Circumstances where a given exception object is
341 * repeatedly caught and rethrown, such as to implement control
342 * flow between two sub-systems, is another situation where
343 * immutable throwable objects would be appropriate.
345 * @param message the detail message.
346 * @param cause the cause. (A {@code null} value is permitted,
347 * and indicates that the cause is nonexistent or unknown.)
348 * @param enableSuppression whether or not suppression is enabled or disabled
349 * @param writableStackTrace whether or not the stack trace should be
352 * @see OutOfMemoryError
353 * @see NullPointerException
354 * @see ArithmeticException
357 protected Throwable(String message, Throwable cause,
358 boolean enableSuppression,
359 boolean writableStackTrace) {
360 if (writableStackTrace) {
365 detailMessage = message;
367 // if (!enableSuppression)
368 // suppressedExceptions = null;
372 * Returns the detail message string of this throwable.
374 * @return the detail message string of this {@code Throwable} instance
375 * (which may be {@code null}).
377 public String getMessage() {
378 return detailMessage;
382 * Creates a localized description of this throwable.
383 * Subclasses may override this method in order to produce a
384 * locale-specific message. For subclasses that do not override this
385 * method, the default implementation returns the same result as
386 * {@code getMessage()}.
388 * @return The localized description of this throwable.
391 public String getLocalizedMessage() {
396 * Returns the cause of this throwable or {@code null} if the
397 * cause is nonexistent or unknown. (The cause is the throwable that
398 * caused this throwable to get thrown.)
400 * <p>This implementation returns the cause that was supplied via one of
401 * the constructors requiring a {@code Throwable}, or that was set after
402 * creation with the {@link #initCause(Throwable)} method. While it is
403 * typically unnecessary to override this method, a subclass can override
404 * it to return a cause set by some other means. This is appropriate for
405 * a "legacy chained throwable" that predates the addition of chained
406 * exceptions to {@code Throwable}. Note that it is <i>not</i>
407 * necessary to override any of the {@code PrintStackTrace} methods,
408 * all of which invoke the {@code getCause} method to determine the
409 * cause of a throwable.
411 * @return the cause of this throwable or {@code null} if the
412 * cause is nonexistent or unknown.
415 public synchronized Throwable getCause() {
416 return (cause==this ? null : cause);
420 * Initializes the <i>cause</i> of this throwable to the specified value.
421 * (The cause is the throwable that caused this throwable to get thrown.)
423 * <p>This method can be called at most once. It is generally called from
424 * within the constructor, or immediately after creating the
425 * throwable. If this throwable was created
426 * with {@link #Throwable(Throwable)} or
427 * {@link #Throwable(String,Throwable)}, this method cannot be called
430 * <p>An example of using this method on a legacy throwable type
431 * without other support for setting the cause is:
436 * } catch (LowLevelException le) {
437 * throw (HighLevelException)
438 * new HighLevelException().initCause(le); // Legacy constructor
442 * @param cause the cause (which is saved for later retrieval by the
443 * {@link #getCause()} method). (A {@code null} value is
444 * permitted, and indicates that the cause is nonexistent or
446 * @return a reference to this {@code Throwable} instance.
447 * @throws IllegalArgumentException if {@code cause} is this
448 * throwable. (A throwable cannot be its own cause.)
449 * @throws IllegalStateException if this throwable was
450 * created with {@link #Throwable(Throwable)} or
451 * {@link #Throwable(String,Throwable)}, or this method has already
452 * been called on this throwable.
455 public synchronized Throwable initCause(Throwable cause) {
456 if (this.cause != this)
457 throw new IllegalStateException("Can't overwrite cause");
459 throw new IllegalArgumentException("Self-causation not permitted");
465 * Returns a short description of this throwable.
466 * The result is the concatenation of:
468 * <li> the {@linkplain Class#getName() name} of the class of this object
469 * <li> ": " (a colon and a space)
470 * <li> the result of invoking this object's {@link #getLocalizedMessage}
473 * If {@code getLocalizedMessage} returns {@code null}, then just
474 * the class name is returned.
476 * @return a string representation of this throwable.
478 public String toString() {
479 String s = getClass().getName();
480 String message = getLocalizedMessage();
481 return (message != null) ? (s + ": " + message) : s;
485 * Prints this throwable and its backtrace to the
486 * standard error stream. This method prints a stack trace for this
487 * {@code Throwable} object on the error output stream that is
488 * the value of the field {@code System.err}. The first line of
489 * output contains the result of the {@link #toString()} method for
490 * this object. Remaining lines represent data previously recorded by
491 * the method {@link #fillInStackTrace()}. The format of this
492 * information depends on the implementation, but the following
493 * example may be regarded as typical:
495 * java.lang.NullPointerException
496 * at MyClass.mash(MyClass.java:9)
497 * at MyClass.crunch(MyClass.java:6)
498 * at MyClass.main(MyClass.java:3)
499 * </pre></blockquote>
500 * This example was produced by running the program:
503 * public static void main(String[] args) {
506 * static void crunch(int[] a) {
509 * static void mash(int[] b) {
510 * System.out.println(b[0]);
514 * The backtrace for a throwable with an initialized, non-null cause
515 * should generally include the backtrace for the cause. The format
516 * of this information depends on the implementation, but the following
517 * example may be regarded as typical:
519 * HighLevelException: MidLevelException: LowLevelException
520 * at Junk.a(Junk.java:13)
521 * at Junk.main(Junk.java:4)
522 * Caused by: MidLevelException: LowLevelException
523 * at Junk.c(Junk.java:23)
524 * at Junk.b(Junk.java:17)
525 * at Junk.a(Junk.java:11)
527 * Caused by: LowLevelException
528 * at Junk.e(Junk.java:30)
529 * at Junk.d(Junk.java:27)
530 * at Junk.c(Junk.java:21)
533 * Note the presence of lines containing the characters {@code "..."}.
534 * These lines indicate that the remainder of the stack trace for this
535 * exception matches the indicated number of frames from the bottom of the
536 * stack trace of the exception that was caused by this exception (the
537 * "enclosing" exception). This shorthand can greatly reduce the length
538 * of the output in the common case where a wrapped exception is thrown
539 * from same method as the "causative exception" is caught. The above
540 * example was produced by running the program:
542 * public class Junk {
543 * public static void main(String args[]) {
546 * } catch(HighLevelException e) {
547 * e.printStackTrace();
550 * static void a() throws HighLevelException {
553 * } catch(MidLevelException e) {
554 * throw new HighLevelException(e);
557 * static void b() throws MidLevelException {
560 * static void c() throws MidLevelException {
563 * } catch(LowLevelException e) {
564 * throw new MidLevelException(e);
567 * static void d() throws LowLevelException {
570 * static void e() throws LowLevelException {
571 * throw new LowLevelException();
575 * class HighLevelException extends Exception {
576 * HighLevelException(Throwable cause) { super(cause); }
579 * class MidLevelException extends Exception {
580 * MidLevelException(Throwable cause) { super(cause); }
583 * class LowLevelException extends Exception {
586 * As of release 7, the platform supports the notion of
587 * <i>suppressed exceptions</i> (in conjunction with the {@code
588 * try}-with-resources statement). Any exceptions that were
589 * suppressed in order to deliver an exception are printed out
590 * beneath the stack trace. The format of this information
591 * depends on the implementation, but the following example may be
592 * regarded as typical:
595 * Exception in thread "main" java.lang.Exception: Something happened
596 * at Foo.bar(Foo.java:10)
597 * at Foo.main(Foo.java:5)
598 * Suppressed: Resource$CloseFailException: Resource ID = 0
599 * at Resource.close(Resource.java:26)
600 * at Foo.bar(Foo.java:9)
603 * Note that the "... n more" notation is used on suppressed exceptions
604 * just at it is used on causes. Unlike causes, suppressed exceptions are
605 * indented beyond their "containing exceptions."
607 * <p>An exception can have both a cause and one or more suppressed
610 * Exception in thread "main" java.lang.Exception: Main block
611 * at Foo3.main(Foo3.java:7)
612 * Suppressed: Resource$CloseFailException: Resource ID = 2
613 * at Resource.close(Resource.java:26)
614 * at Foo3.main(Foo3.java:5)
615 * Suppressed: Resource$CloseFailException: Resource ID = 1
616 * at Resource.close(Resource.java:26)
617 * at Foo3.main(Foo3.java:5)
618 * Caused by: java.lang.Exception: I did it
619 * at Foo3.main(Foo3.java:8)
621 * Likewise, a suppressed exception can have a cause:
623 * Exception in thread "main" java.lang.Exception: Main block
624 * at Foo4.main(Foo4.java:6)
625 * Suppressed: Resource2$CloseFailException: Resource ID = 1
626 * at Resource2.close(Resource2.java:20)
627 * at Foo4.main(Foo4.java:5)
628 * Caused by: java.lang.Exception: Rats, you caught me
629 * at Resource2$CloseFailException.<init>(Resource2.java:45)
633 // public void printStackTrace() {
634 // printStackTrace(System.err);
638 // * Prints this throwable and its backtrace to the specified print stream.
640 // * @param s {@code PrintStream} to use for output
642 // public void printStackTrace(PrintStream s) {
643 // printStackTrace(new WrappedPrintStream(s));
646 // private void printStackTrace(PrintStreamOrWriter s) {
647 // // Guard against malicious overrides of Throwable.equals by
648 // // using a Set with identity equality semantics.
649 //// Set<Throwable> dejaVu =
650 //// Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
651 //// dejaVu.add(this);
653 // synchronized (s.lock()) {
654 // // Print our stack trace
656 // StackTraceElement[] trace = getOurStackTrace();
657 // for (StackTraceElement traceElement : trace)
658 // s.println("\tat " + traceElement);
660 // // Print suppressed exceptions, if any
661 //// for (Throwable se : getSuppressed())
662 //// se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
664 // // Print cause, if any
665 // Throwable ourCause = getCause();
666 //// if (ourCause != null)
667 //// ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
672 // * Print our stack trace as an enclosed exception for the specified
675 // private void printEnclosedStackTrace(PrintStreamOrWriter s,
676 // StackTraceElement[] enclosingTrace,
680 // assert Thread.holdsLock(s.lock());
682 // // Compute number of frames in common between this and enclosing trace
683 // StackTraceElement[] trace = getOurStackTrace();
684 // int m = trace.length - 1;
685 // int n = enclosingTrace.length - 1;
686 // while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
689 // int framesInCommon = trace.length - 1 - m;
691 // // Print our stack trace
692 // s.println(prefix + caption + this);
693 // for (int i = 0; i <= m; i++)
694 // s.println(prefix + "\tat " + trace[i]);
695 // if (framesInCommon != 0)
696 // s.println(prefix + "\t... " + framesInCommon + " more");
698 // // Print suppressed exceptions, if any
699 // for (Throwable se : getSuppressed())
700 // se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
701 // prefix +"\t", dejaVu);
703 // // Print cause, if any
704 // Throwable ourCause = getCause();
705 // if (ourCause != null)
706 // ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
711 // * Prints this throwable and its backtrace to the specified
714 // * @param s {@code PrintWriter} to use for output
717 // public void printStackTrace(PrintWriter s) {
718 // printStackTrace(new WrappedPrintWriter(s));
722 // * Wrapper class for PrintStream and PrintWriter to enable a single
723 // * implementation of printStackTrace.
725 // private abstract static class PrintStreamOrWriter {
726 // /** Returns the object to be locked when using this StreamOrWriter */
727 // abstract Object lock();
729 // /** Prints the specified string as a line on this StreamOrWriter */
730 // abstract void println(Object o);
733 // private static class WrappedPrintStream extends PrintStreamOrWriter {
734 // private final PrintStream printStream;
736 // WrappedPrintStream(PrintStream printStream) {
737 // this.printStream = printStream;
741 // return printStream;
744 // void println(Object o) {
745 // printStream.println(o);
749 // private static class WrappedPrintWriter extends PrintStreamOrWriter {
750 // private final PrintWriter printWriter;
752 // WrappedPrintWriter(PrintWriter printWriter) {
753 // this.printWriter = printWriter;
757 // return printWriter;
760 // void println(Object o) {
761 // printWriter.println(o);
766 * Fills in the execution stack trace. This method records within this
767 * {@code Throwable} object information about the current state of
768 * the stack frames for the current thread.
770 * <p>If the stack trace of this {@code Throwable} {@linkplain
771 * Throwable#Throwable(String, Throwable, boolean, boolean) is not
772 * writable}, calling this method has no effect.
774 * @return a reference to this {@code Throwable} instance.
775 * @see java.lang.Throwable#printStackTrace()
777 public synchronized Throwable fillInStackTrace() {
778 if (stackTrace != null ||
779 backtrace != null /* Out of protocol state */ ) {
781 stackTrace = UNASSIGNED_STACK;
786 @JavaScriptBody(args = { "self", "dummy" }, body = "")
787 private native Throwable fillInStackTrace(int dummy);
790 * Provides programmatic access to the stack trace information printed by
791 * {@link #printStackTrace()}. Returns an array of stack trace elements,
792 * each representing one stack frame. The zeroth element of the array
793 * (assuming the array's length is non-zero) represents the top of the
794 * stack, which is the last method invocation in the sequence. Typically,
795 * this is the point at which this throwable was created and thrown.
796 * The last element of the array (assuming the array's length is non-zero)
797 * represents the bottom of the stack, which is the first method invocation
800 * <p>Some virtual machines may, under some circumstances, omit one
801 * or more stack frames from the stack trace. In the extreme case,
802 * a virtual machine that has no stack trace information concerning
803 * this throwable is permitted to return a zero-length array from this
804 * method. Generally speaking, the array returned by this method will
805 * contain one element for every frame that would be printed by
806 * {@code printStackTrace}. Writes to the returned array do not
807 * affect future calls to this method.
809 * @return an array of stack trace elements representing the stack trace
810 * pertaining to this throwable.
813 public StackTraceElement[] getStackTrace() {
814 return getOurStackTrace().clone();
817 private synchronized StackTraceElement[] getOurStackTrace() {
818 // Initialize stack trace field with information from
819 // backtrace if this is the first call to this method
820 if (stackTrace == UNASSIGNED_STACK ||
821 (stackTrace == null && backtrace != null) /* Out of protocol state */) {
822 int depth = getStackTraceDepth();
823 stackTrace = new StackTraceElement[depth];
824 for (int i=0; i < depth; i++)
825 stackTrace[i] = getStackTraceElement(i);
826 } else if (stackTrace == null) {
827 return UNASSIGNED_STACK;
833 * Sets the stack trace elements that will be returned by
834 * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
835 * and related methods.
837 * This method, which is designed for use by RPC frameworks and other
838 * advanced systems, allows the client to override the default
839 * stack trace that is either generated by {@link #fillInStackTrace()}
840 * when a throwable is constructed or deserialized when a throwable is
841 * read from a serialization stream.
843 * <p>If the stack trace of this {@code Throwable} {@linkplain
844 * Throwable#Throwable(String, Throwable, boolean, boolean) is not
845 * writable}, calling this method has no effect other than
846 * validating its argument.
848 * @param stackTrace the stack trace elements to be associated with
849 * this {@code Throwable}. The specified array is copied by this
850 * call; changes in the specified array after the method invocation
851 * returns will have no affect on this {@code Throwable}'s stack
854 * @throws NullPointerException if {@code stackTrace} is
855 * {@code null} or if any of the elements of
856 * {@code stackTrace} are {@code null}
860 public void setStackTrace(StackTraceElement[] stackTrace) {
862 StackTraceElement[] defensiveCopy = stackTrace.clone();
863 for (int i = 0; i < defensiveCopy.length; i++) {
864 if (defensiveCopy[i] == null)
865 throw new NullPointerException("stackTrace[" + i + "]");
868 synchronized (this) {
869 if (this.stackTrace == null && // Immutable stack
870 backtrace == null) // Test for out of protocol state
872 this.stackTrace = defensiveCopy;
877 * Returns the number of elements in the stack trace (or 0 if the stack
878 * trace is unavailable).
880 * package-protection for use by SharedSecrets.
882 native int getStackTraceDepth();
885 * Returns the specified element of the stack trace.
887 * package-protection for use by SharedSecrets.
889 * @param index index of the element to return.
890 * @throws IndexOutOfBoundsException if {@code index < 0 ||
891 * index >= getStackTraceDepth() }
893 native StackTraceElement getStackTraceElement(int index);
896 * Reads a {@code Throwable} from a stream, enforcing
897 * well-formedness constraints on fields. Null entries and
898 * self-pointers are not allowed in the list of {@code
899 * suppressedExceptions}. Null entries are not allowed for stack
900 * trace elements. A null stack trace in the serial form results
901 * in a zero-length stack element array. A single-element stack
902 * trace whose entry is equal to {@code new StackTraceElement("",
903 * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
906 * Note that there are no constraints on the value the {@code
907 * cause} field can hold; both {@code null} and {@code this} are
908 * valid values for the field.
910 // private void readObject(ObjectInputStream s)
911 // throws IOException, ClassNotFoundException {
912 // s.defaultReadObject(); // read in all fields
913 // if (suppressedExceptions != null) {
914 // List<Throwable> suppressed = null;
915 // if (suppressedExceptions.isEmpty()) {
916 // // Use the sentinel for a zero-length list
917 // suppressed = SUPPRESSED_SENTINEL;
918 // } else { // Copy Throwables to new list
919 // suppressed = new ArrayList<Throwable>(1);
920 // for (Throwable t : suppressedExceptions) {
921 // // Enforce constraints on suppressed exceptions in
922 // // case of corrupt or malicious stream.
924 // throw new NullPointerException(NULL_CAUSE_MESSAGE);
926 // throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
927 // suppressed.add(t);
930 // suppressedExceptions = suppressed;
931 // } // else a null suppressedExceptions field remains null
934 // * For zero-length stack traces, use a clone of
935 // * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
936 // * allow identity comparison against UNASSIGNED_STACK in
937 // * getOurStackTrace. The identity of UNASSIGNED_STACK in
938 // * stackTrace indicates to the getOurStackTrace method that
939 // * the stackTrace needs to be constructed from the information
942 // if (stackTrace != null) {
943 // if (stackTrace.length == 0) {
944 // stackTrace = UNASSIGNED_STACK.clone();
945 // } else if (stackTrace.length == 1 &&
946 // // Check for the marker of an immutable stack trace
947 // SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) {
948 // stackTrace = null;
949 // } else { // Verify stack trace elements are non-null.
950 // for(StackTraceElement ste : stackTrace) {
952 // throw new NullPointerException("null StackTraceElement in serial stream. ");
956 // // A null stackTrace field in the serial form can result
957 // // from an exception serialized without that field in
958 // // older JDK releases; treat such exceptions as having
959 // // empty stack traces.
960 // stackTrace = UNASSIGNED_STACK.clone();
965 * Write a {@code Throwable} object to a stream.
967 * A {@code null} stack trace field is represented in the serial
968 * form as a one-element array whose element is equal to {@code
969 * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
971 // private synchronized void writeObject(ObjectOutputStream s)
972 // throws IOException {
973 // // Ensure that the stackTrace field is initialized to a
974 // // non-null value, if appropriate. As of JDK 7, a null stack
975 // // trace field is a valid value indicating the stack trace
976 // // should not be set.
977 // getOurStackTrace();
979 // StackTraceElement[] oldStackTrace = stackTrace;
981 // if (stackTrace == null)
982 // stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
983 // s.defaultWriteObject();
985 // stackTrace = oldStackTrace;
990 * Appends the specified exception to the exceptions that were
991 * suppressed in order to deliver this exception. This method is
992 * thread-safe and typically called (automatically and implicitly)
993 * by the {@code try}-with-resources statement.
995 * <p>The suppression behavior is enabled <em>unless</em> disabled
996 * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
997 * a constructor}. When suppression is disabled, this method does
998 * nothing other than to validate its argument.
1000 * <p>Note that when one exception {@linkplain
1001 * #initCause(Throwable) causes} another exception, the first
1002 * exception is usually caught and then the second exception is
1003 * thrown in response. In other words, there is a causal
1004 * connection between the two exceptions.
1006 * In contrast, there are situations where two independent
1007 * exceptions can be thrown in sibling code blocks, in particular
1008 * in the {@code try} block of a {@code try}-with-resources
1009 * statement and the compiler-generated {@code finally} block
1010 * which closes the resource.
1012 * In these situations, only one of the thrown exceptions can be
1013 * propagated. In the {@code try}-with-resources statement, when
1014 * there are two such exceptions, the exception originating from
1015 * the {@code try} block is propagated and the exception from the
1016 * {@code finally} block is added to the list of exceptions
1017 * suppressed by the exception from the {@code try} block. As an
1018 * exception unwinds the stack, it can accumulate multiple
1019 * suppressed exceptions.
1021 * <p>An exception may have suppressed exceptions while also being
1022 * caused by another exception. Whether or not an exception has a
1023 * cause is semantically known at the time of its creation, unlike
1024 * whether or not an exception will suppress other exceptions
1025 * which is typically only determined after an exception is
1028 * <p>Note that programmer written code is also able to take
1029 * advantage of calling this method in situations where there are
1030 * multiple sibling exceptions and only one can be propagated.
1032 * @param exception the exception to be added to the list of
1033 * suppressed exceptions
1034 * @throws IllegalArgumentException if {@code exception} is this
1035 * throwable; a throwable cannot suppress itself.
1036 * @throws NullPointerException if {@code exception} is {@code null}
1039 public final synchronized void addSuppressed(Throwable exception) {
1040 if (exception == this)
1041 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
1043 if (exception == null)
1044 throw new NullPointerException(NULL_CAUSE_MESSAGE);
1046 // if (suppressedExceptions == null) // Suppressed exceptions not recorded
1049 // if (suppressedExceptions == SUPPRESSED_SENTINEL)
1050 // suppressedExceptions = new ArrayList<Throwable>(1);
1052 // suppressedExceptions.add(exception);
1055 private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
1058 * Returns an array containing all of the exceptions that were
1059 * suppressed, typically by the {@code try}-with-resources
1060 * statement, in order to deliver this exception.
1062 * If no exceptions were suppressed or {@linkplain
1063 * #Throwable(String, Throwable, boolean, boolean) suppression is
1064 * disabled}, an empty array is returned. This method is
1065 * thread-safe. Writes to the returned array do not affect future
1066 * calls to this method.
1068 * @return an array containing all of the exceptions that were
1069 * suppressed to deliver this exception.
1072 public final synchronized Throwable[] getSuppressed() {
1073 return new Throwable[0];
1074 // if (suppressedExceptions == SUPPRESSED_SENTINEL ||
1075 // suppressedExceptions == null)
1076 // return EMPTY_THROWABLE_ARRAY;
1078 // return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);