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