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