1 /* 2 * Copyright (c) 1994, 2011, 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 * @jls3 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 value indicating that the logical stack trace has been 158 * populated into the backtrace field. 159 */ 160 private static final StackTraceElement[] FILLED_IN_STACK = 161 new StackTraceElement[] {new StackTraceElement("FILLED_IN", "STACK", null, -1)}; 162 163 /** 164 * A shared value for an empty stack. 165 */ 166 private static final StackTraceElement[] EMPTY_STACK = new StackTraceElement[0]; 167 168 /* 169 * To allow Throwable objects to be made immutable and safely 170 * reused by the JVM, such as OutOfMemoryErrors, fields of 171 * Throwable that are writable in response to user actions, cause, 172 * stackTrace, and suppressedExceptions obey the following 173 * protocol: 174 * 175 * 1) The fields are initialized to a non-null sentinel value 176 * which indicates the value has logically not been set. 177 * 178 * 2) Writing a null to the field indicates further writes 179 * are forbidden 180 * 181 * 3) The sentinel value may be replaced with another non-null 182 * value. 183 * 184 * For example, implementations of the HotSpot JVM have 185 * preallocated OutOfMemoryError objects to provide for better 186 * diagnosability of that situation. These objects are created 187 * without calling the constructor for that class and the fields 188 * in question are initialized to null. To support this 189 * capability, any new fields added to Throwable that require 190 * being initialized to a non-null value require a coordinated JVM 191 * change. 192 */ 193 194 /** 195 * The throwable that caused this throwable to get thrown, or null if this 196 * throwable was not caused by another throwable, or if the causative 197 * throwable is unknown. If this field is equal to this throwable itself, 198 * it indicates that the cause of this throwable has not yet been 199 * initialized. 200 * 201 * @serial 202 * @since 1.4 203 */ 204 private Throwable cause = this; 205 206 /** 207 * The stack trace, as returned by {@link #getStackTrace()}. 208 * 209 * The field is initialized to a zero-length array. A {@code 210 * null} value of this field indicates subsequent calls to {@link 211 * #setStackTrace()} and {@link #fillInStackTrace} will be be no-ops. 212 * 213 * @serial 214 * @since 1.4 215 */ 216 private StackTraceElement[] stackTrace = EMPTY_STACK; 217 218 // Setting this static field introduces an acceptable 219 // initialization dependency on a few java.util classes. 220 private static final List<Throwable> SUPPRESSED_SENTINEL = 221 Collections.unmodifiableList(new ArrayList<Throwable>(0)); 222 223 /** 224 * The list of suppressed exceptions, as returned by {@link 225 * #getSuppressed()}. The list is initialized to a zero-element 226 * unmodifiable sentinel list. When a serialized Throwable is 227 * read in, if the {@code suppressedExceptions} field points to a 228 * zero-element list, the field is reset to the sentinel value. 229 * 230 * @serial 231 * @since 1.7 232 */ 233 private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL; 234 235 /** Message for trying to suppress a null exception. */ 236 private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception."; 237 238 /** Message for trying to suppress oneself. */ 239 private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted"; 240 241 /** Caption for labeling causative exception stack traces */ 242 private static final String CAUSE_CAPTION = "Caused by: "; 243 244 /** Caption for labeling suppressed exception stack traces */ 245 private static final String SUPPRESSED_CAPTION = "Suppressed: "; 246 247 /** 248 * Constructs a new throwable with {@code null} as its detail message. 249 * The cause is not initialized, and may subsequently be initialized by a 250 * call to {@link #initCause}. 251 * 252 * <p>The {@link #fillInStackTrace()} method is called to initialize 253 * the stack trace data in the newly created throwable. 254 */ 255 public Throwable() { 256 fillInStackTrace(); 257 } 258 259 /** 260 * Constructs a new throwable with the specified detail message. The 261 * cause is not initialized, and may subsequently be initialized by 262 * a call to {@link #initCause}. 263 * 264 * <p>The {@link #fillInStackTrace()} method is called to initialize 265 * the stack trace data in the newly created throwable. 266 * 267 * @param message the detail message. The detail message is saved for 268 * later retrieval by the {@link #getMessage()} method. 269 */ 270 public Throwable(String message) { 271 fillInStackTrace(); 272 detailMessage = message; 273 } 274 275 /** 276 * Constructs a new throwable with the specified detail message and 277 * cause. <p>Note that the detail message associated with 278 * {@code cause} is <i>not</i> automatically incorporated in 279 * this throwable's detail message. 280 * 281 * <p>The {@link #fillInStackTrace()} method is called to initialize 282 * the stack trace data in the newly created throwable. 283 * 284 * @param message the detail message (which is saved for later retrieval 285 * by the {@link #getMessage()} method). 286 * @param cause the cause (which is saved for later retrieval by the 287 * {@link #getCause()} method). (A {@code null} value is 288 * permitted, and indicates that the cause is nonexistent or 289 * unknown.) 290 * @since 1.4 291 */ 292 public Throwable(String message, Throwable cause) { 293 fillInStackTrace(); 294 detailMessage = message; 295 this.cause = cause; 296 } 297 298 /** 299 * Constructs a new throwable with the specified cause and a detail 300 * message of {@code (cause==null ? null : cause.toString())} (which 301 * typically contains the class and detail message of {@code cause}). 302 * This constructor is useful for throwables that are little more than 303 * wrappers for other throwables (for example, {@link 304 * java.security.PrivilegedActionException}). 305 * 306 * <p>The {@link #fillInStackTrace()} method is called to initialize 307 * the stack trace data in the newly created throwable. 308 * 309 * @param cause the cause (which is saved for later retrieval by the 310 * {@link #getCause()} method). (A {@code null} value is 311 * permitted, and indicates that the cause is nonexistent or 312 * unknown.) 313 * @since 1.4 314 */ 315 public Throwable(Throwable cause) { 316 fillInStackTrace(); 317 detailMessage = (cause==null ? null : cause.toString()); 318 this.cause = cause; 319 } 320 321 /** 322 * Constructs a new throwable with the specified detail message, 323 * cause, {@linkplain #addSuppressed suppression} enabled or 324 * disabled, and writable stack trace enabled or disabled. If 325 * suppression is disabled, {@link #getSuppressed} for this object 326 * will return a zero-length array and calls to {@link 327 * #addSuppressed} that would otherwise append an exception to the 328 * suppressed list will have no effect. If the writable stack 329 * trace is false, this constructor will not call {@link 330 * #fillInStackTrace()} and subsequent calls to {@code 331 * fillInStackTrace} and {@link 332 * #setStackTrace(StackTraceElement[])} will not set the stack 333 * trace. If the writable stack trace is false, {@link 334 * #getStackTrace} will return a zero length array. 335 * 336 * <p>Note that the other constructors of {@code Throwable} treat 337 * suppression as being enabled and the stack trace as being 338 * writable. Subclasses of {@code Throwable} should document any 339 * conditions under which suppression is disabled. Disabling of 340 * suppression should only occur in exceptional circumstances 341 * where special requirements exist, such as a virtual machine 342 * reusing exception objects under low-memory situations. 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 * @param cause the cause (which is saved for later retrieval by the 430 * {@link #getCause()} method). (A {@code null} value is 431 * permitted, and indicates that the cause is nonexistent or 432 * unknown.) 433 * @return a reference to this {@code Throwable} instance. 434 * @throws IllegalArgumentException if {@code cause} is this 435 * throwable. (A throwable cannot be its own cause.) 436 * @throws IllegalStateException if this throwable was 437 * created with {@link #Throwable(Throwable)} or 438 * {@link #Throwable(String,Throwable)}, or this method has already 439 * been called on this throwable. 440 * @since 1.4 441 */ 442 public synchronized Throwable initCause(Throwable cause) { 443 if (this.cause != this) 444 throw new IllegalStateException("Can't overwrite cause"); 445 if (cause == this) 446 throw new IllegalArgumentException("Self-causation not permitted"); 447 this.cause = cause; 448 return this; 449 } 450 451 /** 452 * Returns a short description of this throwable. 453 * The result is the concatenation of: 454 * <ul> 455 * <li> the {@linkplain Class#getName() name} of the class of this object 456 * <li> ": " (a colon and a space) 457 * <li> the result of invoking this object's {@link #getLocalizedMessage} 458 * method 459 * </ul> 460 * If {@code getLocalizedMessage} returns {@code null}, then just 461 * the class name is returned. 462 * 463 * @return a string representation of this throwable. 464 */ 465 public String toString() { 466 String s = getClass().getName(); 467 String message = getLocalizedMessage(); 468 return (message != null) ? (s + ": " + message) : s; 469 } 470 471 /** 472 * Prints this throwable and its backtrace to the 473 * standard error stream. This method prints a stack trace for this 474 * {@code Throwable} object on the error output stream that is 475 * the value of the field {@code System.err}. The first line of 476 * output contains the result of the {@link #toString()} method for 477 * this object. Remaining lines represent data previously recorded by 478 * the method {@link #fillInStackTrace()}. The format of this 479 * information depends on the implementation, but the following 480 * example may be regarded as typical: 481 * <blockquote><pre> 482 * java.lang.NullPointerException 483 * at MyClass.mash(MyClass.java:9) 484 * at MyClass.crunch(MyClass.java:6) 485 * at MyClass.main(MyClass.java:3) 486 * </pre></blockquote> 487 * This example was produced by running the program: 488 * <pre> 489 * class MyClass { 490 * public static void main(String[] args) { 491 * crunch(null); 492 * } 493 * static void crunch(int[] a) { 494 * mash(a); 495 * } 496 * static void mash(int[] b) { 497 * System.out.println(b[0]); 498 * } 499 * } 500 * </pre> 501 * The backtrace for a throwable with an initialized, non-null cause 502 * should generally include the backtrace for the cause. The format 503 * of this information depends on the implementation, but the following 504 * example may be regarded as typical: 505 * <pre> 506 * HighLevelException: MidLevelException: LowLevelException 507 * at Junk.a(Junk.java:13) 508 * at Junk.main(Junk.java:4) 509 * Caused by: MidLevelException: LowLevelException 510 * at Junk.c(Junk.java:23) 511 * at Junk.b(Junk.java:17) 512 * at Junk.a(Junk.java:11) 513 * ... 1 more 514 * Caused by: LowLevelException 515 * at Junk.e(Junk.java:30) 516 * at Junk.d(Junk.java:27) 517 * at Junk.c(Junk.java:21) 518 * ... 3 more 519 * </pre> 520 * Note the presence of lines containing the characters {@code "..."}. 521 * These lines indicate that the remainder of the stack trace for this 522 * exception matches the indicated number of frames from the bottom of the 523 * stack trace of the exception that was caused by this exception (the 524 * "enclosing" exception). This shorthand can greatly reduce the length 525 * of the output in the common case where a wrapped exception is thrown 526 * from same method as the "causative exception" is caught. The above 527 * example was produced by running the program: 528 * <pre> 529 * public class Junk { 530 * public static void main(String args[]) { 531 * try { 532 * a(); 533 * } catch(HighLevelException e) { 534 * e.printStackTrace(); 535 * } 536 * } 537 * static void a() throws HighLevelException { 538 * try { 539 * b(); 540 * } catch(MidLevelException e) { 541 * throw new HighLevelException(e); 542 * } 543 * } 544 * static void b() throws MidLevelException { 545 * c(); 546 * } 547 * static void c() throws MidLevelException { 548 * try { 549 * d(); 550 * } catch(LowLevelException e) { 551 * throw new MidLevelException(e); 552 * } 553 * } 554 * static void d() throws LowLevelException { 555 * e(); 556 * } 557 * static void e() throws LowLevelException { 558 * throw new LowLevelException(); 559 * } 560 * } 561 * 562 * class HighLevelException extends Exception { 563 * HighLevelException(Throwable cause) { super(cause); } 564 * } 565 * 566 * class MidLevelException extends Exception { 567 * MidLevelException(Throwable cause) { super(cause); } 568 * } 569 * 570 * class LowLevelException extends Exception { 571 * } 572 * </pre> 573 * As of release 7, the platform supports the notion of 574 * <i>suppressed exceptions</i> (in conjunction with the {@code 575 * try}-with-resources statement). Any exceptions that were 576 * suppressed in order to deliver an exception are printed out 577 * beneath the stack trace. The format of this information 578 * depends on the implementation, but the following example may be 579 * regarded as typical: 580 * 581 * <pre> 582 * Exception in thread "main" java.lang.Exception: Something happened 583 * at Foo.bar(Foo.java:10) 584 * at Foo.main(Foo.java:5) 585 * Suppressed: Resource$CloseFailException: Resource ID = 0 586 * at Resource.close(Resource.java:26) 587 * at Foo.bar(Foo.java:9) 588 * ... 1 more 589 * </pre> 590 * Note that the "... n more" notation is used on suppressed exceptions 591 * just at it is used on causes. Unlike causes, suppressed exceptions are 592 * indented beyond their "containing exceptions." 593 * 594 * <p>An exception can have both a cause and one or more suppressed 595 * exceptions: 596 * <pre> 597 * Exception in thread "main" java.lang.Exception: Main block 598 * at Foo3.main(Foo3.java:7) 599 * Suppressed: Resource$CloseFailException: Resource ID = 2 600 * at Resource.close(Resource.java:26) 601 * at Foo3.main(Foo3.java:5) 602 * Suppressed: Resource$CloseFailException: Resource ID = 1 603 * at Resource.close(Resource.java:26) 604 * at Foo3.main(Foo3.java:5) 605 * Caused by: java.lang.Exception: I did it 606 * at Foo3.main(Foo3.java:8) 607 * </pre> 608 * Likewise, a suppressed exception can have a cause: 609 * <pre> 610 * Exception in thread "main" java.lang.Exception: Main block 611 * at Foo4.main(Foo4.java:6) 612 * Suppressed: Resource2$CloseFailException: Resource ID = 1 613 * at Resource2.close(Resource2.java:20) 614 * at Foo4.main(Foo4.java:5) 615 * Caused by: java.lang.Exception: Rats, you caught me 616 * at Resource2$CloseFailException.<init>(Resource2.java:45) 617 * ... 2 more 618 * </pre> 619 */ 620 public void printStackTrace() { 621 printStackTrace(System.err); 622 } 623 624 /** 625 * Prints this throwable and its backtrace to the specified print stream. 626 * 627 * @param s {@code PrintStream} to use for output 628 */ 629 public void printStackTrace(PrintStream s) { 630 printStackTrace(new WrappedPrintStream(s)); 631 } 632 633 private void printStackTrace(PrintStreamOrWriter s) { 634 // Guard against malicious overrides of Throwable.equals by 635 // using a Set with identity equality semantics. 636 Set<Throwable> dejaVu = 637 Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>()); 638 dejaVu.add(this); 639 640 synchronized (s.lock()) { 641 // Print our stack trace 642 s.println(this); 643 StackTraceElement[] trace = getOurStackTrace(); 644 for (StackTraceElement traceElement : trace) 645 s.println("\tat " + traceElement); 646 647 // Print suppressed exceptions, if any 648 for (Throwable se : getSuppressed()) 649 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu); 650 651 // Print cause, if any 652 Throwable ourCause = getCause(); 653 if (ourCause != null) 654 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu); 655 } 656 } 657 658 /** 659 * Print our stack trace as an enclosed exception for the specified 660 * stack trace. 661 */ 662 private void printEnclosedStackTrace(PrintStreamOrWriter s, 663 StackTraceElement[] enclosingTrace, 664 String caption, 665 String prefix, 666 Set<Throwable> dejaVu) { 667 assert Thread.holdsLock(s.lock()); 668 if (dejaVu.contains(this)) { 669 s.println("\t[CIRCULAR REFERENCE:" + this + "]"); 670 } else { 671 dejaVu.add(this); 672 // Compute number of frames in common between this and enclosing trace 673 StackTraceElement[] trace = getOurStackTrace(); 674 int m = trace.length - 1; 675 int n = enclosingTrace.length - 1; 676 while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) { 677 m--; n--; 678 } 679 int framesInCommon = trace.length - 1 - m; 680 681 // Print our stack trace 682 s.println(prefix + caption + this); 683 for (int i = 0; i <= m; i++) 684 s.println(prefix + "\tat " + trace[i]); 685 if (framesInCommon != 0) 686 s.println(prefix + "\t... " + framesInCommon + " more"); 687 688 // Print suppressed exceptions, if any 689 for (Throwable se : getSuppressed()) 690 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, 691 prefix +"\t", dejaVu); 692 693 // Print cause, if any 694 Throwable ourCause = getCause(); 695 if (ourCause != null) 696 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu); 697 } 698 } 699 700 /** 701 * Prints this throwable and its backtrace to the specified 702 * print writer. 703 * 704 * @param s {@code PrintWriter} to use for output 705 * @since JDK1.1 706 */ 707 public void printStackTrace(PrintWriter s) { 708 printStackTrace(new WrappedPrintWriter(s)); 709 } 710 711 /** 712 * Wrapper class for PrintStream and PrintWriter to enable a single 713 * implementation of printStackTrace. 714 */ 715 private abstract static class PrintStreamOrWriter { 716 /** Returns the object to be locked when using this StreamOrWriter */ 717 abstract Object lock(); 718 719 /** Prints the specified string as a line on this StreamOrWriter */ 720 abstract void println(Object o); 721 } 722 723 private static class WrappedPrintStream extends PrintStreamOrWriter { 724 private final PrintStream printStream; 725 726 WrappedPrintStream(PrintStream printStream) { 727 this.printStream = printStream; 728 } 729 730 Object lock() { 731 return printStream; 732 } 733 734 void println(Object o) { 735 printStream.println(o); 736 } 737 } 738 739 private static class WrappedPrintWriter extends PrintStreamOrWriter { 740 private final PrintWriter printWriter; 741 742 WrappedPrintWriter(PrintWriter printWriter) { 743 this.printWriter = printWriter; 744 } 745 746 Object lock() { 747 return printWriter; 748 } 749 750 void println(Object o) { 751 printWriter.println(o); 752 } 753 } 754 755 /** 756 * Fills in the execution stack trace. This method records within this 757 * {@code Throwable} object information about the current state of 758 * the stack frames for the current thread. 759 * 760 * <p>If the stack trace of this {@code Throwable} {@linkplain 761 * Throwable#Throwable(String, Throwable, boolean, boolean) is not 762 * writable}, calling this method has no effect. 763 * 764 * @return a reference to this {@code Throwable} instance. 765 * @see java.lang.Throwable#printStackTrace() 766 */ 767 public synchronized Throwable fillInStackTrace() { 768 if (stackTrace != null) { 769 fillInStackTrace(0); 770 stackTrace = FILLED_IN_STACK; 771 } 772 return this; 773 } 774 775 private native Throwable fillInStackTrace(int dummy); 776 777 /** 778 * Provides programmatic access to the stack trace information printed by 779 * {@link #printStackTrace()}. Returns an array of stack trace elements, 780 * each representing one stack frame. The zeroth element of the array 781 * (assuming the array's length is non-zero) represents the top of the 782 * stack, which is the last method invocation in the sequence. Typically, 783 * this is the point at which this throwable was created and thrown. 784 * The last element of the array (assuming the array's length is non-zero) 785 * represents the bottom of the stack, which is the first method invocation 786 * in the sequence. 787 * 788 * <p>Some virtual machines may, under some circumstances, omit one 789 * or more stack frames from the stack trace. In the extreme case, 790 * a virtual machine that has no stack trace information concerning 791 * this throwable is permitted to return a zero-length array from this 792 * method. Generally speaking, the array returned by this method will 793 * contain one element for every frame that would be printed by 794 * {@code printStackTrace}. 795 * 796 * @return an array of stack trace elements representing the stack trace 797 * pertaining to this throwable. 798 * @since 1.4 799 */ 800 public StackTraceElement[] getStackTrace() { 801 return getOurStackTrace().clone(); 802 } 803 804 private synchronized StackTraceElement[] getOurStackTrace() { 805 // Initialize stack trace field with information from 806 // backtrace if this is the first call to this method 807 if (stackTrace == FILLED_IN_STACK) { 808 int depth = getStackTraceDepth(); 809 stackTrace = new StackTraceElement[depth]; 810 for (int i=0; i < depth; i++) 811 stackTrace[i] = getStackTraceElement(i); 812 } else if (stackTrace == null) { 813 return EMPTY_STACK; 814 } 815 return stackTrace; 816 } 817 818 /** 819 * Sets the stack trace elements that will be returned by 820 * {@link #getStackTrace()} and printed by {@link #printStackTrace()} 821 * and related methods. 822 * 823 * This method, which is designed for use by RPC frameworks and other 824 * advanced systems, allows the client to override the default 825 * stack trace that is either generated by {@link #fillInStackTrace()} 826 * when a throwable is constructed or deserialized when a throwable is 827 * read from a serialization stream. 828 * 829 * <p>If the stack trace of this {@code Throwable} {@linkplain 830 * Throwable#Throwable(String, Throwable, boolean, boolean) is not 831 * writable}, calling this method has no effect other than 832 * validating its argument. 833 * 834 * @param stackTrace the stack trace elements to be associated with 835 * this {@code Throwable}. The specified array is copied by this 836 * call; changes in the specified array after the method invocation 837 * returns will have no affect on this {@code Throwable}'s stack 838 * trace. 839 * 840 * @throws NullPointerException if {@code stackTrace} is 841 * {@code null} or if any of the elements of 842 * {@code stackTrace} are {@code null} 843 * 844 * @since 1.4 845 */ 846 public void setStackTrace(StackTraceElement[] stackTrace) { 847 Objects.requireNonNull(stackTrace); 848 849 if (this.stackTrace == null) // Immutable stack 850 return; 851 852 StackTraceElement[] defensiveCopy = stackTrace.clone(); 853 for (int i = 0; i < defensiveCopy.length; i++) { 854 if (defensiveCopy[i] == null) 855 throw new NullPointerException("stackTrace[" + i + "]"); 856 } 857 858 synchronized (this) { 859 this.stackTrace = defensiveCopy; 860 } 861 } 862 863 /** 864 * Returns the number of elements in the stack trace (or 0 if the stack 865 * trace is unavailable). 866 * 867 * package-protection for use by SharedSecrets. 868 */ 869 native int getStackTraceDepth(); 870 871 /** 872 * Returns the specified element of the stack trace. 873 * 874 * package-protection for use by SharedSecrets. 875 * 876 * @param index index of the element to return. 877 * @throws IndexOutOfBoundsException if {@code index < 0 || 878 * index >= getStackTraceDepth() } 879 */ 880 native StackTraceElement getStackTraceElement(int index); 881 882 /** 883 * Reads a {@code Throwable} from a stream, enforcing 884 * well-formedness constraints on fields. Null entries and 885 * self-pointers are not allowed in the list of {@code 886 * suppressedExceptions}. Null entries are not allowed for stack 887 * trace elements. A single-element stack trace whose entry is 888 * equal to {@code new StackTraceElement("", "", null, 889 * Integer.MIN_VALUE)} results in a {@code null} {@code 890 * stackTrace} field. 891 * 892 * Note that there are no constraints on the value the {@code 893 * cause} field can hold; both {@code null} and {@code this} are 894 * valid values for the field. 895 */ 896 private void readObject(ObjectInputStream s) 897 throws IOException, ClassNotFoundException { 898 s.defaultReadObject(); // read in all fields 899 if (suppressedExceptions != null) { 900 List<Throwable> suppressed = null; 901 if (suppressedExceptions.isEmpty()) { 902 // Use the sentinel for a zero-length list 903 suppressed = SUPPRESSED_SENTINEL; 904 } else { // Copy Throwables to new list 905 suppressed = new ArrayList<>(1); 906 for (Throwable t : suppressedExceptions) { 907 // Enforce constraints on suppressed exceptions in 908 // case of corrupt or malicious stream. 909 if (t == null) 910 throw new NullPointerException(NULL_CAUSE_MESSAGE); 911 if (t == this) 912 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); 913 suppressed.add(t); 914 } 915 } 916 suppressedExceptions = suppressed; 917 } // else a null suppressedExceptions field remains null 918 919 // Check for the marker of an immutable stack trace 920 if (stackTrace != null) { 921 // Share zero-length stack traces 922 if (stackTrace.length == 0) { 923 stackTrace = EMPTY_STACK; 924 } else if (stackTrace.length == 1 && 925 SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) { 926 stackTrace = null; 927 } else { // Verify stack trace elements are non-null. 928 for(StackTraceElement ste : stackTrace) { 929 if (ste == null) 930 throw new NullPointerException("null StackTraceElement in serial stream. "); 931 } 932 } 933 } 934 // A null stackTrace field in the serial form can result from 935 // an exception serialized without that field. Such exceptions 936 // are now treated as having immutable stack traces. 937 } 938 939 /** 940 * Write a {@code Throwable} object to a stream. 941 * 942 * A {@code null} stack trace field is represented in the serial 943 * form as a one-element array whose element is equal to {@code 944 * new StackTraceElement("", "", null, Integer.MIN_VALUE)}. 945 */ 946 private synchronized void writeObject(ObjectOutputStream s) 947 throws IOException { 948 // Ensure that the stackTrace field is initialized to a 949 // non-null value, if appropriate. As of JDK 7, a null stack 950 // trace field is a valid value indicating the stack trace 951 // should not be set. 952 getOurStackTrace(); 953 ObjectOutputStream.PutField fields = s.putFields(); 954 955 fields.put("detailMessage", detailMessage); 956 fields.put("cause", cause); 957 // Serialize a null stacktrace using the stack trace sentinel. 958 if (stackTrace == null) 959 fields.put("stackTrace", SentinelHolder.STACK_TRACE_SENTINEL); 960 else 961 fields.put("stackTrace", stackTrace); 962 fields.put("suppressedExceptions", suppressedExceptions); 963 964 s.writeFields(); 965 } 966 967 /** 968 * Appends the specified exception to the exceptions that were 969 * suppressed in order to deliver this exception. This method is 970 * typically called (automatically and implicitly) by the {@code 971 * try}-with-resources statement. 972 * 973 * <p>The suppression behavior is enabled <em>unless</em> disabled 974 * {@linkplain #Throwable(String, Throwable, boolean) via a 975 * constructor}. When suppression is disabled, this method does 976 * nothing other than to validate its argument. 977 * 978 * <p>Note that when one exception {@linkplain 979 * #initCause(Throwable) causes} another exception, the first 980 * exception is usually caught and then the second exception is 981 * thrown in response. In other words, there is a causal 982 * connection between the two exceptions. 983 * 984 * In contrast, there are situations where two independent 985 * exceptions can be thrown in sibling code blocks, in particular 986 * in the {@code try} block of a {@code try}-with-resources 987 * statement and the compiler-generated {@code finally} block 988 * which closes the resource. 989 * 990 * In these situations, only one of the thrown exceptions can be 991 * propagated. In the {@code try}-with-resources statement, when 992 * there are two such exceptions, the exception originating from 993 * the {@code try} block is propagated and the exception from the 994 * {@code finally} block is added to the list of exceptions 995 * suppressed by the exception from the {@code try} block. As an 996 * exception unwinds the stack, it can accumulate multiple 997 * suppressed exceptions. 998 * 999 * <p>An exception may have suppressed exceptions while also being 1000 * caused by another exception. Whether or not an exception has a 1001 * cause is semantically known at the time of its creation, unlike 1002 * whether or not an exception will suppress other exceptions 1003 * which is typically only determined after an exception is 1004 * thrown. 1005 * 1006 * <p>Note that programmer written code is also able to take 1007 * advantage of calling this method in situations where there are 1008 * multiple sibling exceptions and only one can be propagated. 1009 * 1010 * @param exception the exception to be added to the list of 1011 * suppressed exceptions 1012 * @throws IllegalArgumentException if {@code exception} is this 1013 * throwable; a throwable cannot suppress itself. 1014 * @throws NullPointerException if {@code exception} is {@code null} 1015 * @since 1.7 1016 */ 1017 public final synchronized void addSuppressed(Throwable exception) { 1018 if (exception == this) 1019 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); 1020 1021 if (exception == null) 1022 throw new NullPointerException(NULL_CAUSE_MESSAGE); 1023 1024 if (suppressedExceptions == null) // Suppressed exceptions not recorded 1025 return; 1026 1027 if (suppressedExceptions == SUPPRESSED_SENTINEL) 1028 suppressedExceptions = new ArrayList<>(1); 1029 1030 suppressedExceptions.add(exception); 1031 } 1032 1033 private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0]; 1034 1035 /** 1036 * Returns an array containing all of the exceptions that were 1037 * suppressed, typically by the {@code try}-with-resources 1038 * statement, in order to deliver this exception. 1039 * 1040 * If no exceptions were suppressed or {@linkplain 1041 * #Throwable(String, Throwable, boolean) suppression is disabled}, 1042 * an empty array is returned. 1043 * 1044 * @return an array containing all of the exceptions that were 1045 * suppressed to deliver this exception. 1046 * @since 1.7 1047 */ 1048 public final synchronized Throwable[] getSuppressed() { 1049 if (suppressedExceptions == SUPPRESSED_SENTINEL || 1050 suppressedExceptions == null) 1051 return EMPTY_THROWABLE_ARRAY; 1052 else 1053 return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY); 1054 } 1055 }