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