1 /*
2  * Copyright (c) 1994, 2019, 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 
28 import java.io.*;
29 import java.util.*;
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     private static final List<Throwable> SUPPRESSED_SENTINEL =
216         Collections.unmodifiableList(new ArrayList<Throwable>(0));
217 
218     /**
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.
224      *
225      * @serial
226      * @since 1.7
227      */
228     private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
229 
230     /** Message for trying to suppress a null exception. */
231     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
232 
233     /** Message for trying to suppress oneself. */
234     private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
235 
236     /** Caption  for labeling causative exception stack traces */
237     private static final String CAUSE_CAPTION = "Caused by: ";
238 
239     /** Caption for labeling suppressed exception stack traces */
240     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
241 
242     /**
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}.
246      *
247      * <p>The {@link #fillInStackTrace()} method is called to initialize
248      * the stack trace data in the newly created throwable.
249      */
Throwable()250     public Throwable() {
251         fillInStackTrace();
252     }
253 
254     /**
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}.
258      *
259      * <p>The {@link #fillInStackTrace()} method is called to initialize
260      * the stack trace data in the newly created throwable.
261      *
262      * @param   message   the detail message. The detail message is saved for
263      *          later retrieval by the {@link #getMessage()} method.
264      */
Throwable(String message)265     public Throwable(String message) {
266         fillInStackTrace();
267         detailMessage = message;
268     }
269 
270     /**
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.
275      *
276      * <p>The {@link #fillInStackTrace()} method is called to initialize
277      * the stack trace data in the newly created throwable.
278      *
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
284      *         unknown.)
285      * @since  1.4
286      */
Throwable(String message, Throwable cause)287     public Throwable(String message, Throwable cause) {
288         fillInStackTrace();
289         detailMessage = message;
290         this.cause = cause;
291     }
292 
293     /**
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}).
300      *
301      * <p>The {@link #fillInStackTrace()} method is called to initialize
302      * the stack trace data in the newly created throwable.
303      *
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
307      *         unknown.)
308      * @since  1.4
309      */
Throwable(Throwable cause)310     public Throwable(Throwable cause) {
311         fillInStackTrace();
312         detailMessage = (cause==null ? null : cause.toString());
313         this.cause = cause;
314     }
315 
316     /**
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.
331      *
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.
344      *
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
350      *                           writable
351      *
352      * @see OutOfMemoryError
353      * @see NullPointerException
354      * @see ArithmeticException
355      * @since 1.7
356      */
Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)357     protected Throwable(String message, Throwable cause,
358                         boolean enableSuppression,
359                         boolean writableStackTrace) {
360         if (writableStackTrace) {
361             fillInStackTrace();
362         } else {
363             stackTrace = null;
364         }
365         detailMessage = message;
366         this.cause = cause;
367         if (!enableSuppression)
368             suppressedExceptions = null;
369     }
370 
371     /**
372      * Returns the detail message string of this throwable.
373      *
374      * @return  the detail message string of this {@code Throwable} instance
375      *          (which may be {@code null}).
376      */
getMessage()377     public String getMessage() {
378         return detailMessage;
379     }
380 
381     /**
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()}.
387      *
388      * @return  The localized description of this throwable.
389      * @since   JDK1.1
390      */
getLocalizedMessage()391     public String getLocalizedMessage() {
392         return getMessage();
393     }
394 
395     /**
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.)
399      *
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.
410      *
411      * @return  the cause of this throwable or {@code null} if the
412      *          cause is nonexistent or unknown.
413      * @since 1.4
414      */
getCause()415     public synchronized Throwable getCause() {
416         return (cause==this ? null : cause);
417     }
418 
419     /**
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.)
422      *
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
428      * even once.
429      *
430      * <p>An example of using this method on a legacy throwable type
431      * without other support for setting the cause is:
432      *
433      * <pre>
434      * try {
435      *     lowLevelOp();
436      * } catch (LowLevelException le) {
437      *     throw (HighLevelException)
438      *           new HighLevelException().initCause(le); // Legacy constructor
439      * }
440      * </pre>
441      *
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
445      *         unknown.)
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.
453      * @since  1.4
454      */
initCause(Throwable cause)455     public synchronized Throwable initCause(Throwable cause) {
456         if (this.cause != this)
457             throw new IllegalStateException("Can't overwrite cause with " +
458                                             Objects.toString(cause, "a null"), this);
459         if (cause == this)
460             throw new IllegalArgumentException("Self-causation not permitted", this);
461         this.cause = cause;
462         return this;
463     }
464 
465     /**
466      * Returns a short description of this throwable.
467      * The result is the concatenation of:
468      * <ul>
469      * <li> the {@linkplain Class#getName() name} of the class of this object
470      * <li> ": " (a colon and a space)
471      * <li> the result of invoking this object's {@link #getLocalizedMessage}
472      *      method
473      * </ul>
474      * If {@code getLocalizedMessage} returns {@code null}, then just
475      * the class name is returned.
476      *
477      * @return a string representation of this throwable.
478      */
toString()479     public String toString() {
480         String s = getClass().getName();
481         String message = getLocalizedMessage();
482         return (message != null) ? (s + ": " + message) : s;
483     }
484 
485     /**
486      * Prints this throwable and its backtrace to the
487      * standard error stream. This method prints a stack trace for this
488      * {@code Throwable} object on the error output stream that is
489      * the value of the field {@code System.err}. The first line of
490      * output contains the result of the {@link #toString()} method for
491      * this object.  Remaining lines represent data previously recorded by
492      * the method {@link #fillInStackTrace()}. The format of this
493      * information depends on the implementation, but the following
494      * example may be regarded as typical:
495      * <blockquote><pre>
496      * java.lang.NullPointerException
497      *         at MyClass.mash(MyClass.java:9)
498      *         at MyClass.crunch(MyClass.java:6)
499      *         at MyClass.main(MyClass.java:3)
500      * </pre></blockquote>
501      * This example was produced by running the program:
502      * <pre>
503      * class MyClass {
504      *     public static void main(String[] args) {
505      *         crunch(null);
506      *     }
507      *     static void crunch(int[] a) {
508      *         mash(a);
509      *     }
510      *     static void mash(int[] b) {
511      *         System.out.println(b[0]);
512      *     }
513      * }
514      * </pre>
515      * The backtrace for a throwable with an initialized, non-null cause
516      * should generally include the backtrace for the cause.  The format
517      * of this information depends on the implementation, but the following
518      * example may be regarded as typical:
519      * <pre>
520      * HighLevelException: MidLevelException: LowLevelException
521      *         at Junk.a(Junk.java:13)
522      *         at Junk.main(Junk.java:4)
523      * Caused by: MidLevelException: LowLevelException
524      *         at Junk.c(Junk.java:23)
525      *         at Junk.b(Junk.java:17)
526      *         at Junk.a(Junk.java:11)
527      *         ... 1 more
528      * Caused by: LowLevelException
529      *         at Junk.e(Junk.java:30)
530      *         at Junk.d(Junk.java:27)
531      *         at Junk.c(Junk.java:21)
532      *         ... 3 more
533      * </pre>
534      * Note the presence of lines containing the characters {@code "..."}.
535      * These lines indicate that the remainder of the stack trace for this
536      * exception matches the indicated number of frames from the bottom of the
537      * stack trace of the exception that was caused by this exception (the
538      * "enclosing" exception).  This shorthand can greatly reduce the length
539      * of the output in the common case where a wrapped exception is thrown
540      * from same method as the "causative exception" is caught.  The above
541      * example was produced by running the program:
542      * <pre>
543      * public class Junk {
544      *     public static void main(String args[]) {
545      *         try {
546      *             a();
547      *         } catch(HighLevelException e) {
548      *             e.printStackTrace();
549      *         }
550      *     }
551      *     static void a() throws HighLevelException {
552      *         try {
553      *             b();
554      *         } catch(MidLevelException e) {
555      *             throw new HighLevelException(e);
556      *         }
557      *     }
558      *     static void b() throws MidLevelException {
559      *         c();
560      *     }
561      *     static void c() throws MidLevelException {
562      *         try {
563      *             d();
564      *         } catch(LowLevelException e) {
565      *             throw new MidLevelException(e);
566      *         }
567      *     }
568      *     static void d() throws LowLevelException {
569      *        e();
570      *     }
571      *     static void e() throws LowLevelException {
572      *         throw new LowLevelException();
573      *     }
574      * }
575      *
576      * class HighLevelException extends Exception {
577      *     HighLevelException(Throwable cause) { super(cause); }
578      * }
579      *
580      * class MidLevelException extends Exception {
581      *     MidLevelException(Throwable cause)  { super(cause); }
582      * }
583      *
584      * class LowLevelException extends Exception {
585      * }
586      * </pre>
587      * As of release 7, the platform supports the notion of
588      * <i>suppressed exceptions</i> (in conjunction with the {@code
589      * try}-with-resources statement). Any exceptions that were
590      * suppressed in order to deliver an exception are printed out
591      * beneath the stack trace.  The format of this information
592      * depends on the implementation, but the following example may be
593      * regarded as typical:
594      *
595      * <pre>
596      * Exception in thread "main" java.lang.Exception: Something happened
597      *  at Foo.bar(Foo.java:10)
598      *  at Foo.main(Foo.java:5)
599      *  Suppressed: Resource$CloseFailException: Resource ID = 0
600      *          at Resource.close(Resource.java:26)
601      *          at Foo.bar(Foo.java:9)
602      *          ... 1 more
603      * </pre>
604      * Note that the "... n more" notation is used on suppressed exceptions
605      * just at it is used on causes. Unlike causes, suppressed exceptions are
606      * indented beyond their "containing exceptions."
607      *
608      * <p>An exception can have both a cause and one or more suppressed
609      * exceptions:
610      * <pre>
611      * Exception in thread "main" java.lang.Exception: Main block
612      *  at Foo3.main(Foo3.java:7)
613      *  Suppressed: Resource$CloseFailException: Resource ID = 2
614      *          at Resource.close(Resource.java:26)
615      *          at Foo3.main(Foo3.java:5)
616      *  Suppressed: Resource$CloseFailException: Resource ID = 1
617      *          at Resource.close(Resource.java:26)
618      *          at Foo3.main(Foo3.java:5)
619      * Caused by: java.lang.Exception: I did it
620      *  at Foo3.main(Foo3.java:8)
621      * </pre>
622      * Likewise, a suppressed exception can have a cause:
623      * <pre>
624      * Exception in thread "main" java.lang.Exception: Main block
625      *  at Foo4.main(Foo4.java:6)
626      *  Suppressed: Resource2$CloseFailException: Resource ID = 1
627      *          at Resource2.close(Resource2.java:20)
628      *          at Foo4.main(Foo4.java:5)
629      *  Caused by: java.lang.Exception: Rats, you caught me
630      *          at Resource2$CloseFailException.&lt;init&gt;(Resource2.java:45)
631      *          ... 2 more
632      * </pre>
633      */
printStackTrace()634     public void printStackTrace() {
635         printStackTrace(System.err);
636     }
637 
638     /**
639      * Prints this throwable and its backtrace to the specified print stream.
640      *
641      * @param s {@code PrintStream} to use for output
642      */
printStackTrace(PrintStream s)643     public void printStackTrace(PrintStream s) {
644         printStackTrace(new WrappedPrintStream(s));
645     }
646 
printStackTrace(PrintStreamOrWriter s)647     private void printStackTrace(PrintStreamOrWriter s) {
648         // Guard against malicious overrides of Throwable.equals by
649         // using a Set with identity equality semantics.
650         Set<Throwable> dejaVu =
651             Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
652         dejaVu.add(this);
653 
654         synchronized (s.lock()) {
655             // Print our stack trace
656             s.println(this);
657             StackTraceElement[] trace = getOurStackTrace();
658             for (StackTraceElement traceElement : trace)
659                 s.println("\tat " + traceElement);
660 
661             // Print suppressed exceptions, if any
662             for (Throwable se : getSuppressed())
663                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
664 
665             // Print cause, if any
666             Throwable ourCause = getCause();
667             if (ourCause != null)
668                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
669         }
670     }
671 
672     /**
673      * Print our stack trace as an enclosed exception for the specified
674      * stack trace.
675      */
printEnclosedStackTrace(PrintStreamOrWriter s, StackTraceElement[] enclosingTrace, String caption, String prefix, Set<Throwable> dejaVu)676     private void printEnclosedStackTrace(PrintStreamOrWriter s,
677                                          StackTraceElement[] enclosingTrace,
678                                          String caption,
679                                          String prefix,
680                                          Set<Throwable> dejaVu) {
681         assert Thread.holdsLock(s.lock());
682         if (dejaVu.contains(this)) {
683             s.println(prefix + caption + "[CIRCULAR REFERENCE: " + this + "]");
684         } else {
685             dejaVu.add(this);
686             // Compute number of frames in common between this and enclosing trace
687             StackTraceElement[] trace = getOurStackTrace();
688             int m = trace.length - 1;
689             int n = enclosingTrace.length - 1;
690             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
691                 m--; n--;
692             }
693             int framesInCommon = trace.length - 1 - m;
694 
695             // Print our stack trace
696             s.println(prefix + caption + this);
697             for (int i = 0; i <= m; i++)
698                 s.println(prefix + "\tat " + trace[i]);
699             if (framesInCommon != 0)
700                 s.println(prefix + "\t... " + framesInCommon + " more");
701 
702             // Print suppressed exceptions, if any
703             for (Throwable se : getSuppressed())
704                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
705                                            prefix +"\t", dejaVu);
706 
707             // Print cause, if any
708             Throwable ourCause = getCause();
709             if (ourCause != null)
710                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
711         }
712     }
713 
714     /**
715      * Prints this throwable and its backtrace to the specified
716      * print writer.
717      *
718      * @param s {@code PrintWriter} to use for output
719      * @since   JDK1.1
720      */
printStackTrace(PrintWriter s)721     public void printStackTrace(PrintWriter s) {
722         printStackTrace(new WrappedPrintWriter(s));
723     }
724 
725     /**
726      * Wrapper class for PrintStream and PrintWriter to enable a single
727      * implementation of printStackTrace.
728      */
729     private abstract static class PrintStreamOrWriter {
730         /** Returns the object to be locked when using this StreamOrWriter */
lock()731         abstract Object lock();
732 
733         /** Prints the specified string as a line on this StreamOrWriter */
println(Object o)734         abstract void println(Object o);
735     }
736 
737     private static class WrappedPrintStream extends PrintStreamOrWriter {
738         private final PrintStream printStream;
739 
WrappedPrintStream(PrintStream printStream)740         WrappedPrintStream(PrintStream printStream) {
741             this.printStream = printStream;
742         }
743 
lock()744         Object lock() {
745             return printStream;
746         }
747 
println(Object o)748         void println(Object o) {
749             printStream.println(o);
750         }
751     }
752 
753     private static class WrappedPrintWriter extends PrintStreamOrWriter {
754         private final PrintWriter printWriter;
755 
WrappedPrintWriter(PrintWriter printWriter)756         WrappedPrintWriter(PrintWriter printWriter) {
757             this.printWriter = printWriter;
758         }
759 
lock()760         Object lock() {
761             return printWriter;
762         }
763 
println(Object o)764         void println(Object o) {
765             printWriter.println(o);
766         }
767     }
768 
769     /**
770      * Fills in the execution stack trace. This method records within this
771      * {@code Throwable} object information about the current state of
772      * the stack frames for the current thread.
773      *
774      * <p>If the stack trace of this {@code Throwable} {@linkplain
775      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
776      * writable}, calling this method has no effect.
777      *
778      * @return  a reference to this {@code Throwable} instance.
779      * @see     java.lang.Throwable#printStackTrace()
780      */
fillInStackTrace()781     public synchronized Throwable fillInStackTrace() {
782         if (stackTrace != null ||
783             backtrace != null /* Out of protocol state */ ) {
784             fillInStackTrace(0);
785             stackTrace = UNASSIGNED_STACK;
786         }
787         return this;
788     }
789 
fillInStackTrace(int dummy)790     private native Throwable fillInStackTrace(int dummy);
791 
792     /**
793      * Provides programmatic access to the stack trace information printed by
794      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
795      * each representing one stack frame.  The zeroth element of the array
796      * (assuming the array's length is non-zero) represents the top of the
797      * stack, which is the last method invocation in the sequence.  Typically,
798      * this is the point at which this throwable was created and thrown.
799      * The last element of the array (assuming the array's length is non-zero)
800      * represents the bottom of the stack, which is the first method invocation
801      * in the sequence.
802      *
803      * <p>Some virtual machines may, under some circumstances, omit one
804      * or more stack frames from the stack trace.  In the extreme case,
805      * a virtual machine that has no stack trace information concerning
806      * this throwable is permitted to return a zero-length array from this
807      * method.  Generally speaking, the array returned by this method will
808      * contain one element for every frame that would be printed by
809      * {@code printStackTrace}.  Writes to the returned array do not
810      * affect future calls to this method.
811      *
812      * @return an array of stack trace elements representing the stack trace
813      *         pertaining to this throwable.
814      * @since  1.4
815      */
getStackTrace()816     public StackTraceElement[] getStackTrace() {
817         return getOurStackTrace().clone();
818     }
819 
getOurStackTrace()820     private synchronized StackTraceElement[] getOurStackTrace() {
821         // Initialize stack trace field with information from
822         // backtrace if this is the first call to this method
823         if (stackTrace == UNASSIGNED_STACK ||
824             (stackTrace == null && backtrace != null) /* Out of protocol state */) {
825             int depth = getStackTraceDepth();
826             stackTrace = new StackTraceElement[depth];
827             for (int i=0; i < depth; i++)
828                 stackTrace[i] = getStackTraceElement(i);
829         } else if (stackTrace == null) {
830             return UNASSIGNED_STACK;
831         }
832         return stackTrace;
833     }
834 
835     /**
836      * Sets the stack trace elements that will be returned by
837      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
838      * and related methods.
839      *
840      * This method, which is designed for use by RPC frameworks and other
841      * advanced systems, allows the client to override the default
842      * stack trace that is either generated by {@link #fillInStackTrace()}
843      * when a throwable is constructed or deserialized when a throwable is
844      * read from a serialization stream.
845      *
846      * <p>If the stack trace of this {@code Throwable} {@linkplain
847      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
848      * writable}, calling this method has no effect other than
849      * validating its argument.
850      *
851      * @param   stackTrace the stack trace elements to be associated with
852      * this {@code Throwable}.  The specified array is copied by this
853      * call; changes in the specified array after the method invocation
854      * returns will have no affect on this {@code Throwable}'s stack
855      * trace.
856      *
857      * @throws NullPointerException if {@code stackTrace} is
858      *         {@code null} or if any of the elements of
859      *         {@code stackTrace} are {@code null}
860      *
861      * @since  1.4
862      */
setStackTrace(StackTraceElement[] stackTrace)863     public void setStackTrace(StackTraceElement[] stackTrace) {
864         // Validate argument
865         StackTraceElement[] defensiveCopy = stackTrace.clone();
866         for (int i = 0; i < defensiveCopy.length; i++) {
867             if (defensiveCopy[i] == null)
868                 throw new NullPointerException("stackTrace[" + i + "]");
869         }
870 
871         synchronized (this) {
872             if (this.stackTrace == null && // Immutable stack
873                 backtrace == null) // Test for out of protocol state
874                 return;
875             this.stackTrace = defensiveCopy;
876         }
877     }
878 
879     /**
880      * Returns the number of elements in the stack trace (or 0 if the stack
881      * trace is unavailable).
882      *
883      * package-protection for use by SharedSecrets.
884      */
getStackTraceDepth()885     native int getStackTraceDepth();
886 
887     /**
888      * Returns the specified element of the stack trace.
889      *
890      * package-protection for use by SharedSecrets.
891      *
892      * @param index index of the element to return.
893      * @throws IndexOutOfBoundsException if {@code index < 0 ||
894      *         index >= getStackTraceDepth() }
895      */
getStackTraceElement(int index)896     native StackTraceElement getStackTraceElement(int index);
897 
898     /**
899      * Reads a {@code Throwable} from a stream, enforcing
900      * well-formedness constraints on fields.  Null entries and
901      * self-pointers are not allowed in the list of {@code
902      * suppressedExceptions}.  Null entries are not allowed for stack
903      * trace elements.  A null stack trace in the serial form results
904      * in a zero-length stack element array. A single-element stack
905      * trace whose entry is equal to {@code new StackTraceElement("",
906      * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
907      * stackTrace} field.
908      *
909      * Note that there are no constraints on the value the {@code
910      * cause} field can hold; both {@code null} and {@code this} are
911      * valid values for the field.
912      */
readObject(ObjectInputStream s)913     private void readObject(ObjectInputStream s)
914         throws IOException, ClassNotFoundException {
915         s.defaultReadObject();     // read in all fields
916 
917         // Set suppressed exceptions and stack trace elements fields
918         // to marker values until the contents from the serial stream
919         // are validated.
920         List<Throwable> candidateSuppressedExceptions = suppressedExceptions;
921         suppressedExceptions = SUPPRESSED_SENTINEL;
922 
923         StackTraceElement[] candidateStackTrace = stackTrace;
924         stackTrace = UNASSIGNED_STACK.clone();
925 
926         if (candidateSuppressedExceptions != null) {
927             int suppressedSize = validateSuppressedExceptionsList(candidateSuppressedExceptions);
928             if (suppressedSize > 0) { // Copy valid Throwables to new list
929                 List<Throwable> suppList  = new ArrayList<Throwable>(Math.min(100, suppressedSize));
930 
931                 for (Throwable t : candidateSuppressedExceptions) {
932                     // Enforce constraints on suppressed exceptions in
933                     // case of corrupt or malicious stream.
934                     if (t == null)
935                         throw new NullPointerException(NULL_CAUSE_MESSAGE);
936                     if (t == this)
937                         throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
938                     suppList.add(t);
939                 }
940                 // If there are any invalid suppressed exceptions,
941                 // implicitly use the sentinel value assigned earlier.
942                 suppressedExceptions = suppList;
943             }
944         } else {
945             suppressedExceptions = null;
946         }
947 
948         /*
949          * For zero-length stack traces, use a clone of
950          * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
951          * allow identity comparison against UNASSIGNED_STACK in
952          * getOurStackTrace.  The identity of UNASSIGNED_STACK in
953          * stackTrace indicates to the getOurStackTrace method that
954          * the stackTrace needs to be constructed from the information
955          * in backtrace.
956          */
957         if (candidateStackTrace != null) {
958             // Work from a clone of the candidateStackTrace to ensure
959             // consistency of checks.
960             candidateStackTrace = candidateStackTrace.clone();
961             if (candidateStackTrace.length >= 1) {
962                 if (candidateStackTrace.length == 1 &&
963                         // Check for the marker of an immutable stack trace
964                         SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(candidateStackTrace[0])) {
965                     stackTrace = null;
966                 } else { // Verify stack trace elements are non-null.
967                     for (StackTraceElement ste : candidateStackTrace) {
968                         if (ste == null)
969                             throw new NullPointerException("null StackTraceElement in serial stream.");
970                     }
971                     stackTrace = candidateStackTrace;
972                 }
973             }
974         }
975         // A null stackTrace field in the serial form can result from
976         // an exception serialized without that field in older JDK
977         // releases; treat such exceptions as having empty stack
978         // traces by leaving stackTrace assigned to a clone of
979         // UNASSIGNED_STACK.
980     }
981 
validateSuppressedExceptionsList(List<Throwable> deserSuppressedExceptions)982     private int validateSuppressedExceptionsList(List<Throwable> deserSuppressedExceptions)
983         throws IOException {
984         if (Object.class.getClassLoader() != deserSuppressedExceptions.getClass().getClassLoader()) {
985             throw new StreamCorruptedException("List implementation not on the bootclasspath.");
986         } else {
987             int size = deserSuppressedExceptions.size();
988             if (size < 0) {
989                 throw new StreamCorruptedException("Negative list size reported.");
990             }
991             return size;
992         }
993     }
994 
995     /**
996      * Write a {@code Throwable} object to a stream.
997      *
998      * A {@code null} stack trace field is represented in the serial
999      * form as a one-element array whose element is equal to {@code
1000      * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
1001      */
writeObject(ObjectOutputStream s)1002     private synchronized void writeObject(ObjectOutputStream s)
1003         throws IOException {
1004         // Ensure that the stackTrace field is initialized to a
1005         // non-null value, if appropriate.  As of JDK 7, a null stack
1006         // trace field is a valid value indicating the stack trace
1007         // should not be set.
1008         getOurStackTrace();
1009 
1010         StackTraceElement[] oldStackTrace = stackTrace;
1011         try {
1012             if (stackTrace == null)
1013                 stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
1014             s.defaultWriteObject();
1015         } finally {
1016             stackTrace = oldStackTrace;
1017         }
1018     }
1019 
1020     /**
1021      * Appends the specified exception to the exceptions that were
1022      * suppressed in order to deliver this exception. This method is
1023      * thread-safe and typically called (automatically and implicitly)
1024      * by the {@code try}-with-resources statement.
1025      *
1026      * <p>The suppression behavior is enabled <em>unless</em> disabled
1027      * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
1028      * a constructor}.  When suppression is disabled, this method does
1029      * nothing other than to validate its argument.
1030      *
1031      * <p>Note that when one exception {@linkplain
1032      * #initCause(Throwable) causes} another exception, the first
1033      * exception is usually caught and then the second exception is
1034      * thrown in response.  In other words, there is a causal
1035      * connection between the two exceptions.
1036      *
1037      * In contrast, there are situations where two independent
1038      * exceptions can be thrown in sibling code blocks, in particular
1039      * in the {@code try} block of a {@code try}-with-resources
1040      * statement and the compiler-generated {@code finally} block
1041      * which closes the resource.
1042      *
1043      * In these situations, only one of the thrown exceptions can be
1044      * propagated.  In the {@code try}-with-resources statement, when
1045      * there are two such exceptions, the exception originating from
1046      * the {@code try} block is propagated and the exception from the
1047      * {@code finally} block is added to the list of exceptions
1048      * suppressed by the exception from the {@code try} block.  As an
1049      * exception unwinds the stack, it can accumulate multiple
1050      * suppressed exceptions.
1051      *
1052      * <p>An exception may have suppressed exceptions while also being
1053      * caused by another exception.  Whether or not an exception has a
1054      * cause is semantically known at the time of its creation, unlike
1055      * whether or not an exception will suppress other exceptions
1056      * which is typically only determined after an exception is
1057      * thrown.
1058      *
1059      * <p>Note that programmer written code is also able to take
1060      * advantage of calling this method in situations where there are
1061      * multiple sibling exceptions and only one can be propagated.
1062      *
1063      * @param exception the exception to be added to the list of
1064      *        suppressed exceptions
1065      * @throws IllegalArgumentException if {@code exception} is this
1066      *         throwable; a throwable cannot suppress itself.
1067      * @throws NullPointerException if {@code exception} is {@code null}
1068      * @since 1.7
1069      */
addSuppressed(Throwable exception)1070     public final synchronized void addSuppressed(Throwable exception) {
1071         if (exception == this)
1072             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception);
1073 
1074         if (exception == null)
1075             throw new NullPointerException(NULL_CAUSE_MESSAGE);
1076 
1077         if (suppressedExceptions == null) // Suppressed exceptions not recorded
1078             return;
1079 
1080         if (suppressedExceptions == SUPPRESSED_SENTINEL)
1081             suppressedExceptions = new ArrayList<>(1);
1082 
1083         suppressedExceptions.add(exception);
1084     }
1085 
1086     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
1087 
1088     /**
1089      * Returns an array containing all of the exceptions that were
1090      * suppressed, typically by the {@code try}-with-resources
1091      * statement, in order to deliver this exception.
1092      *
1093      * If no exceptions were suppressed or {@linkplain
1094      * #Throwable(String, Throwable, boolean, boolean) suppression is
1095      * disabled}, an empty array is returned.  This method is
1096      * thread-safe.  Writes to the returned array do not affect future
1097      * calls to this method.
1098      *
1099      * @return an array containing all of the exceptions that were
1100      *         suppressed to deliver this exception.
1101      * @since 1.7
1102      */
getSuppressed()1103     public final synchronized Throwable[] getSuppressed() {
1104         if (suppressedExceptions == SUPPRESSED_SENTINEL ||
1105             suppressedExceptions == null)
1106             return EMPTY_THROWABLE_ARRAY;
1107         else
1108             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
1109     }
1110 }
1111