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
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 private static final List<Throwable> SUPPRESSED_SENTINEL =
215 Collections.unmodifiableList(new ArrayList<Throwable>(0));
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.
227 private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
229 /** Message for trying to suppress a null exception. */
230 private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
232 /** Message for trying to suppress oneself. */
233 private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
235 /** Caption for labeling causative exception stack traces */
236 private static final String CAUSE_CAPTION = "Caused by: ";
238 /** Caption for labeling suppressed exception stack traces */
239 private static final String SUPPRESSED_CAPTION = "Suppressed: ";
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}.
246 * <p>The {@link #fillInStackTrace()} method is called to initialize
247 * the stack trace data in the newly created throwable.
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}.
258 * <p>The {@link #fillInStackTrace()} method is called to initialize
259 * the stack trace data in the newly created throwable.
261 * @param message the detail message. The detail message is saved for
262 * later retrieval by the {@link #getMessage()} method.
264 public Throwable(String message) {
266 detailMessage = message;
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.
275 * <p>The {@link #fillInStackTrace()} method is called to initialize
276 * the stack trace data in the newly created throwable.
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
286 public Throwable(String message, Throwable cause) {
288 detailMessage = message;
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}).
300 * <p>The {@link #fillInStackTrace()} method is called to initialize
301 * the stack trace data in the newly created throwable.
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
309 public Throwable(Throwable cause) {
311 detailMessage = (cause==null ? null : cause.toString());
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.
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.
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
351 * @see OutOfMemoryError
352 * @see NullPointerException
353 * @see ArithmeticException
356 protected Throwable(String message, Throwable cause,
357 boolean enableSuppression,
358 boolean writableStackTrace) {
359 if (writableStackTrace) {
364 detailMessage = message;
366 if (!enableSuppression)
367 suppressedExceptions = null;
371 * Returns the detail message string of this throwable.
373 * @return the detail message string of this {@code Throwable} instance
374 * (which may be {@code null}).
376 public String getMessage() {
377 return detailMessage;
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()}.
387 * @return The localized description of this throwable.
390 public String getLocalizedMessage() {
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.)
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.
410 * @return the cause of this throwable or {@code null} if the
411 * cause is nonexistent or unknown.
414 public synchronized Throwable getCause() {
415 return (cause==this ? null : cause);
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.)
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
429 * <p>An example of using this method on a legacy throwable type
430 * without other support for setting the cause is:
435 * } catch (LowLevelException le) {
436 * throw (HighLevelException)
437 * new HighLevelException().initCause(le); // Legacy constructor
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
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.
454 public synchronized Throwable initCause(Throwable cause) {
455 if (this.cause != this)
456 throw new IllegalStateException("Can't overwrite cause");
458 throw new IllegalArgumentException("Self-causation not permitted");
464 * Returns a short description of this throwable.
465 * The result is the concatenation of:
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}
472 * If {@code getLocalizedMessage} returns {@code null}, then just
473 * the class name is returned.
475 * @return a string representation of this throwable.
477 public String toString() {
478 String s = getClass().getName();
479 String message = getLocalizedMessage();
480 return (message != null) ? (s + ": " + message) : s;
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:
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:
502 * public static void main(String[] args) {
505 * static void crunch(int[] a) {
508 * static void mash(int[] b) {
509 * System.out.println(b[0]);
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:
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)
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)
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:
541 * public class Junk {
542 * public static void main(String args[]) {
545 * } catch(HighLevelException e) {
546 * e.printStackTrace();
549 * static void a() throws HighLevelException {
552 * } catch(MidLevelException e) {
553 * throw new HighLevelException(e);
556 * static void b() throws MidLevelException {
559 * static void c() throws MidLevelException {
562 * } catch(LowLevelException e) {
563 * throw new MidLevelException(e);
566 * static void d() throws LowLevelException {
569 * static void e() throws LowLevelException {
570 * throw new LowLevelException();
574 * class HighLevelException extends Exception {
575 * HighLevelException(Throwable cause) { super(cause); }
578 * class MidLevelException extends Exception {
579 * MidLevelException(Throwable cause) { super(cause); }
582 * class LowLevelException extends Exception {
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:
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)
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."
606 * <p>An exception can have both a cause and one or more suppressed
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)
620 * Likewise, a suppressed exception can have a cause:
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)
632 public void printStackTrace() {
633 printStackTrace(System.err);
637 * Prints this throwable and its backtrace to the specified print stream.
639 * @param s {@code PrintStream} to use for output
641 public void printStackTrace(PrintStream s) {
642 printStackTrace(new WrappedPrintStream(s));
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>());
652 synchronized (s.lock()) {
653 // Print our stack trace
655 StackTraceElement[] trace = getOurStackTrace();
656 for (StackTraceElement traceElement : trace)
657 s.println("\tat " + traceElement);
659 // Print suppressed exceptions, if any
660 for (Throwable se : getSuppressed())
661 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
663 // Print cause, if any
664 Throwable ourCause = getCause();
665 if (ourCause != null)
666 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
671 * Print our stack trace as an enclosed exception for the specified
674 private void printEnclosedStackTrace(PrintStreamOrWriter s,
675 StackTraceElement[] enclosingTrace,
678 Set<Throwable> dejaVu) {
679 assert Thread.holdsLock(s.lock());
680 if (dejaVu.contains(this)) {
681 s.println("\t[CIRCULAR REFERENCE:" + this + "]");
684 // Compute number of frames in common between this and enclosing trace
685 StackTraceElement[] trace = getOurStackTrace();
686 int m = trace.length - 1;
687 int n = enclosingTrace.length - 1;
688 while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
691 int framesInCommon = trace.length - 1 - m;
693 // Print our stack trace
694 s.println(prefix + caption + this);
695 for (int i = 0; i <= m; i++)
696 s.println(prefix + "\tat " + trace[i]);
697 if (framesInCommon != 0)
698 s.println(prefix + "\t... " + framesInCommon + " more");
700 // Print suppressed exceptions, if any
701 for (Throwable se : getSuppressed())
702 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
703 prefix +"\t", dejaVu);
705 // Print cause, if any
706 Throwable ourCause = getCause();
707 if (ourCause != null)
708 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
713 * Prints this throwable and its backtrace to the specified
716 * @param s {@code PrintWriter} to use for output
719 public void printStackTrace(PrintWriter s) {
720 printStackTrace(new WrappedPrintWriter(s));
724 * Wrapper class for PrintStream and PrintWriter to enable a single
725 * implementation of printStackTrace.
727 private abstract static class PrintStreamOrWriter {
728 /** Returns the object to be locked when using this StreamOrWriter */
729 abstract Object lock();
731 /** Prints the specified string as a line on this StreamOrWriter */
732 abstract void println(Object o);
735 private static class WrappedPrintStream extends PrintStreamOrWriter {
736 private final PrintStream printStream;
738 WrappedPrintStream(PrintStream printStream) {
739 this.printStream = printStream;
746 void println(Object o) {
747 printStream.println(o);
751 private static class WrappedPrintWriter extends PrintStreamOrWriter {
752 private final PrintWriter printWriter;
754 WrappedPrintWriter(PrintWriter printWriter) {
755 this.printWriter = printWriter;
762 void println(Object o) {
763 printWriter.println(o);
768 * Fills in the execution stack trace. This method records within this
769 * {@code Throwable} object information about the current state of
770 * the stack frames for the current thread.
772 * <p>If the stack trace of this {@code Throwable} {@linkplain
773 * Throwable#Throwable(String, Throwable, boolean, boolean) is not
774 * writable}, calling this method has no effect.
776 * @return a reference to this {@code Throwable} instance.
777 * @see java.lang.Throwable#printStackTrace()
779 public synchronized Throwable fillInStackTrace() {
780 if (stackTrace != null ||
781 backtrace != null /* Out of protocol state */ ) {
783 stackTrace = UNASSIGNED_STACK;
788 private native Throwable fillInStackTrace(int dummy);
791 * Provides programmatic access to the stack trace information printed by
792 * {@link #printStackTrace()}. Returns an array of stack trace elements,
793 * each representing one stack frame. The zeroth element of the array
794 * (assuming the array's length is non-zero) represents the top of the
795 * stack, which is the last method invocation in the sequence. Typically,
796 * this is the point at which this throwable was created and thrown.
797 * The last element of the array (assuming the array's length is non-zero)
798 * represents the bottom of the stack, which is the first method invocation
801 * <p>Some virtual machines may, under some circumstances, omit one
802 * or more stack frames from the stack trace. In the extreme case,
803 * a virtual machine that has no stack trace information concerning
804 * this throwable is permitted to return a zero-length array from this
805 * method. Generally speaking, the array returned by this method will
806 * contain one element for every frame that would be printed by
807 * {@code printStackTrace}. Writes to the returned array do not
808 * affect future calls to this method.
810 * @return an array of stack trace elements representing the stack trace
811 * pertaining to this throwable.
814 public StackTraceElement[] getStackTrace() {
815 return getOurStackTrace().clone();
818 private synchronized StackTraceElement[] getOurStackTrace() {
819 // Initialize stack trace field with information from
820 // backtrace if this is the first call to this method
821 if (stackTrace == UNASSIGNED_STACK ||
822 (stackTrace == null && backtrace != null) /* Out of protocol state */) {
823 int depth = getStackTraceDepth();
824 stackTrace = new StackTraceElement[depth];
825 for (int i=0; i < depth; i++)
826 stackTrace[i] = getStackTraceElement(i);
827 } else if (stackTrace == null) {
828 return UNASSIGNED_STACK;
834 * Sets the stack trace elements that will be returned by
835 * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
836 * and related methods.
838 * This method, which is designed for use by RPC frameworks and other
839 * advanced systems, allows the client to override the default
840 * stack trace that is either generated by {@link #fillInStackTrace()}
841 * when a throwable is constructed or deserialized when a throwable is
842 * read from a serialization stream.
844 * <p>If the stack trace of this {@code Throwable} {@linkplain
845 * Throwable#Throwable(String, Throwable, boolean, boolean) is not
846 * writable}, calling this method has no effect other than
847 * validating its argument.
849 * @param stackTrace the stack trace elements to be associated with
850 * this {@code Throwable}. The specified array is copied by this
851 * call; changes in the specified array after the method invocation
852 * returns will have no affect on this {@code Throwable}'s stack
855 * @throws NullPointerException if {@code stackTrace} is
856 * {@code null} or if any of the elements of
857 * {@code stackTrace} are {@code null}
861 public void setStackTrace(StackTraceElement[] stackTrace) {
863 StackTraceElement[] defensiveCopy = stackTrace.clone();
864 for (int i = 0; i < defensiveCopy.length; i++) {
865 if (defensiveCopy[i] == null)
866 throw new NullPointerException("stackTrace[" + i + "]");
869 synchronized (this) {
870 if (this.stackTrace == null && // Immutable stack
871 backtrace == null) // Test for out of protocol state
873 this.stackTrace = defensiveCopy;
878 * Returns the number of elements in the stack trace (or 0 if the stack
879 * trace is unavailable).
881 * package-protection for use by SharedSecrets.
883 native int getStackTraceDepth();
886 * Returns the specified element of the stack trace.
888 * package-protection for use by SharedSecrets.
890 * @param index index of the element to return.
891 * @throws IndexOutOfBoundsException if {@code index < 0 ||
892 * index >= getStackTraceDepth() }
894 native StackTraceElement getStackTraceElement(int index);
897 * Reads a {@code Throwable} from a stream, enforcing
898 * well-formedness constraints on fields. Null entries and
899 * self-pointers are not allowed in the list of {@code
900 * suppressedExceptions}. Null entries are not allowed for stack
901 * trace elements. A null stack trace in the serial form results
902 * in a zero-length stack element array. A single-element stack
903 * trace whose entry is equal to {@code new StackTraceElement("",
904 * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
907 * Note that there are no constraints on the value the {@code
908 * cause} field can hold; both {@code null} and {@code this} are
909 * valid values for the field.
911 private void readObject(ObjectInputStream s)
912 throws IOException, ClassNotFoundException {
913 s.defaultReadObject(); // read in all fields
914 if (suppressedExceptions != null) {
915 List<Throwable> suppressed = null;
916 if (suppressedExceptions.isEmpty()) {
917 // Use the sentinel for a zero-length list
918 suppressed = SUPPRESSED_SENTINEL;
919 } else { // Copy Throwables to new list
920 suppressed = new ArrayList<>(1);
921 for (Throwable t : suppressedExceptions) {
922 // Enforce constraints on suppressed exceptions in
923 // case of corrupt or malicious stream.
925 throw new NullPointerException(NULL_CAUSE_MESSAGE);
927 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
931 suppressedExceptions = suppressed;
932 } // else a null suppressedExceptions field remains null
935 * For zero-length stack traces, use a clone of
936 * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
937 * allow identity comparison against UNASSIGNED_STACK in
938 * getOurStackTrace. The identity of UNASSIGNED_STACK in
939 * stackTrace indicates to the getOurStackTrace method that
940 * the stackTrace needs to be constructed from the information
943 if (stackTrace != null) {
944 if (stackTrace.length == 0) {
945 stackTrace = UNASSIGNED_STACK.clone();
946 } else if (stackTrace.length == 1 &&
947 // Check for the marker of an immutable stack trace
948 SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) {
950 } else { // Verify stack trace elements are non-null.
951 for(StackTraceElement ste : stackTrace) {
953 throw new NullPointerException("null StackTraceElement in serial stream. ");
957 // A null stackTrace field in the serial form can result
958 // from an exception serialized without that field in
959 // older JDK releases; treat such exceptions as having
960 // empty stack traces.
961 stackTrace = UNASSIGNED_STACK.clone();
966 * Write a {@code Throwable} object to a stream.
968 * A {@code null} stack trace field is represented in the serial
969 * form as a one-element array whose element is equal to {@code
970 * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
972 private synchronized void writeObject(ObjectOutputStream s)
974 // Ensure that the stackTrace field is initialized to a
975 // non-null value, if appropriate. As of JDK 7, a null stack
976 // trace field is a valid value indicating the stack trace
977 // should not be set.
980 StackTraceElement[] oldStackTrace = stackTrace;
982 if (stackTrace == null)
983 stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
984 s.defaultWriteObject();
986 stackTrace = oldStackTrace;
991 * Appends the specified exception to the exceptions that were
992 * suppressed in order to deliver this exception. This method is
993 * thread-safe and typically called (automatically and implicitly)
994 * by the {@code try}-with-resources statement.
996 * <p>The suppression behavior is enabled <em>unless</em> disabled
997 * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
998 * a constructor}. When suppression is disabled, this method does
999 * nothing other than to validate its argument.
1001 * <p>Note that when one exception {@linkplain
1002 * #initCause(Throwable) causes} another exception, the first
1003 * exception is usually caught and then the second exception is
1004 * thrown in response. In other words, there is a causal
1005 * connection between the two exceptions.
1007 * In contrast, there are situations where two independent
1008 * exceptions can be thrown in sibling code blocks, in particular
1009 * in the {@code try} block of a {@code try}-with-resources
1010 * statement and the compiler-generated {@code finally} block
1011 * which closes the resource.
1013 * In these situations, only one of the thrown exceptions can be
1014 * propagated. In the {@code try}-with-resources statement, when
1015 * there are two such exceptions, the exception originating from
1016 * the {@code try} block is propagated and the exception from the
1017 * {@code finally} block is added to the list of exceptions
1018 * suppressed by the exception from the {@code try} block. As an
1019 * exception unwinds the stack, it can accumulate multiple
1020 * suppressed exceptions.
1022 * <p>An exception may have suppressed exceptions while also being
1023 * caused by another exception. Whether or not an exception has a
1024 * cause is semantically known at the time of its creation, unlike
1025 * whether or not an exception will suppress other exceptions
1026 * which is typically only determined after an exception is
1029 * <p>Note that programmer written code is also able to take
1030 * advantage of calling this method in situations where there are
1031 * multiple sibling exceptions and only one can be propagated.
1033 * @param exception the exception to be added to the list of
1034 * suppressed exceptions
1035 * @throws IllegalArgumentException if {@code exception} is this
1036 * throwable; a throwable cannot suppress itself.
1037 * @throws NullPointerException if {@code exception} is {@code null}
1040 public final synchronized void addSuppressed(Throwable exception) {
1041 if (exception == this)
1042 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
1044 if (exception == null)
1045 throw new NullPointerException(NULL_CAUSE_MESSAGE);
1047 if (suppressedExceptions == null) // Suppressed exceptions not recorded
1050 if (suppressedExceptions == SUPPRESSED_SENTINEL)
1051 suppressedExceptions = new ArrayList<>(1);
1053 suppressedExceptions.add(exception);
1056 private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
1059 * Returns an array containing all of the exceptions that were
1060 * suppressed, typically by the {@code try}-with-resources
1061 * statement, in order to deliver this exception.
1063 * If no exceptions were suppressed or {@linkplain
1064 * #Throwable(String, Throwable, boolean, boolean) suppression is
1065 * disabled}, an empty array is returned. This method is
1066 * thread-safe. Writes to the returned array do not affect future
1067 * calls to this method.
1069 * @return an array containing all of the exceptions that were
1070 * suppressed to deliver this exception.
1073 public final synchronized Throwable[] getSuppressed() {
1074 if (suppressedExceptions == SUPPRESSED_SENTINEL ||
1075 suppressedExceptions == null)
1076 return EMPTY_THROWABLE_ARRAY;
1078 return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);