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