1 /* 2 * Copyright (c) 1994, 2012, 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 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 IllegalStateException ise = new IllegalStateException("Can't overwrite cause"); 457 ise.addSuppressed(this); 458 if (cause != null) 459 ise.addSuppressed(cause); 460 throw ise; 461 } 462 if (cause == this) 463 throw new IllegalArgumentException("Self-causation not permitted", this); 464 this.cause = cause; 465 return this; 466 } 467 468 /** 469 * Returns a short description of this throwable. 470 * The result is the concatenation of: 471 * <ul> 472 * <li> the {@linkplain Class#getName() name} of the class of this object 473 * <li> ": " (a colon and a space) 474 * <li> the result of invoking this object's {@link #getLocalizedMessage} 475 * method 476 * </ul> 477 * If {@code getLocalizedMessage} returns {@code null}, then just 478 * the class name is returned. 479 * 480 * @return a string representation of this throwable. 481 */ 482 public String toString() { 483 String s = getClass().getName(); 484 String message = getLocalizedMessage(); 485 return (message != null) ? (s + ": " + message) : s; 486 } 487 488 /** 489 * Prints this throwable and its backtrace to the 490 * standard error stream. This method prints a stack trace for this 491 * {@code Throwable} object on the error output stream that is 492 * the value of the field {@code System.err}. The first line of 493 * output contains the result of the {@link #toString()} method for 494 * this object. Remaining lines represent data previously recorded by 495 * the method {@link #fillInStackTrace()}. The format of this 496 * information depends on the implementation, but the following 497 * example may be regarded as typical: 498 * <blockquote><pre> 499 * java.lang.NullPointerException 500 * at MyClass.mash(MyClass.java:9) 501 * at MyClass.crunch(MyClass.java:6) 502 * at MyClass.main(MyClass.java:3) 503 * </pre></blockquote> 504 * This example was produced by running the program: 505 * <pre> 506 * class MyClass { 507 * public static void main(String[] args) { 508 * crunch(null); 509 * } 510 * static void crunch(int[] a) { 511 * mash(a); 512 * } 513 * static void mash(int[] b) { 514 * System.out.println(b[0]); 515 * } 516 * } 517 * </pre> 518 * The backtrace for a throwable with an initialized, non-null cause 519 * should generally include the backtrace for the cause. The format 520 * of this information depends on the implementation, but the following 521 * example may be regarded as typical: 522 * <pre> 523 * HighLevelException: MidLevelException: LowLevelException 524 * at Junk.a(Junk.java:13) 525 * at Junk.main(Junk.java:4) 526 * Caused by: MidLevelException: LowLevelException 527 * at Junk.c(Junk.java:23) 528 * at Junk.b(Junk.java:17) 529 * at Junk.a(Junk.java:11) 530 * ... 1 more 531 * Caused by: LowLevelException 532 * at Junk.e(Junk.java:30) 533 * at Junk.d(Junk.java:27) 534 * at Junk.c(Junk.java:21) 535 * ... 3 more 536 * </pre> 537 * Note the presence of lines containing the characters {@code "..."}. 538 * These lines indicate that the remainder of the stack trace for this 539 * exception matches the indicated number of frames from the bottom of the 540 * stack trace of the exception that was caused by this exception (the 541 * "enclosing" exception). This shorthand can greatly reduce the length 542 * of the output in the common case where a wrapped exception is thrown 543 * from same method as the "causative exception" is caught. The above 544 * example was produced by running the program: 545 * <pre> 546 * public class Junk { 547 * public static void main(String args[]) { 548 * try { 549 * a(); 550 * } catch(HighLevelException e) { 551 * e.printStackTrace(); 552 * } 553 * } 554 * static void a() throws HighLevelException { 555 * try { 556 * b(); 557 * } catch(MidLevelException e) { 558 * throw new HighLevelException(e); 559 * } 560 * } 561 * static void b() throws MidLevelException { 562 * c(); 563 * } 564 * static void c() throws MidLevelException { 565 * try { 566 * d(); 567 * } catch(LowLevelException e) { 568 * throw new MidLevelException(e); 569 * } 570 * } 571 * static void d() throws LowLevelException { 572 * e(); 573 * } 574 * static void e() throws LowLevelException { 575 * throw new LowLevelException(); 576 * } 577 * } 578 * 579 * class HighLevelException extends Exception { 580 * HighLevelException(Throwable cause) { super(cause); } 581 * } 582 * 583 * class MidLevelException extends Exception { 584 * MidLevelException(Throwable cause) { super(cause); } 585 * } 586 * 587 * class LowLevelException extends Exception { 588 * } 589 * </pre> 590 * As of release 7, the platform supports the notion of 591 * <i>suppressed exceptions</i> (in conjunction with the {@code 592 * try}-with-resources statement). Any exceptions that were 593 * suppressed in order to deliver an exception are printed out 594 * beneath the stack trace. The format of this information 595 * depends on the implementation, but the following example may be 596 * regarded as typical: 597 * 598 * <pre> 599 * Exception in thread "main" java.lang.Exception: Something happened 600 * at Foo.bar(Foo.java:10) 601 * at Foo.main(Foo.java:5) 602 * Suppressed: Resource$CloseFailException: Resource ID = 0 603 * at Resource.close(Resource.java:26) 604 * at Foo.bar(Foo.java:9) 605 * ... 1 more 606 * </pre> 607 * Note that the "... n more" notation is used on suppressed exceptions 608 * just at it is used on causes. Unlike causes, suppressed exceptions are 609 * indented beyond their "containing exceptions." 610 * 611 * <p>An exception can have both a cause and one or more suppressed 612 * exceptions: 613 * <pre> 614 * Exception in thread "main" java.lang.Exception: Main block 615 * at Foo3.main(Foo3.java:7) 616 * Suppressed: Resource$CloseFailException: Resource ID = 2 617 * at Resource.close(Resource.java:26) 618 * at Foo3.main(Foo3.java:5) 619 * Suppressed: Resource$CloseFailException: Resource ID = 1 620 * at Resource.close(Resource.java:26) 621 * at Foo3.main(Foo3.java:5) 622 * Caused by: java.lang.Exception: I did it 623 * at Foo3.main(Foo3.java:8) 624 * </pre> 625 * Likewise, a suppressed exception can have a cause: 626 * <pre> 627 * Exception in thread "main" java.lang.Exception: Main block 628 * at Foo4.main(Foo4.java:6) 629 * Suppressed: Resource2$CloseFailException: Resource ID = 1 630 * at Resource2.close(Resource2.java:20) 631 * at Foo4.main(Foo4.java:5) 632 * Caused by: java.lang.Exception: Rats, you caught me 633 * at Resource2$CloseFailException.<init>(Resource2.java:45) 634 * ... 2 more 635 * </pre> 636 */ 637 public void printStackTrace() { 638 printStackTrace(System.err); 639 } 640 641 /** 642 * Prints this throwable and its backtrace to the specified print stream. 643 * 644 * @param s {@code PrintStream} to use for output 645 */ 646 public void printStackTrace(PrintStream s) { 647 printStackTrace(new WrappedPrintStream(s)); 648 } 649 650 private void printStackTrace(PrintStreamOrWriter s) { 651 // Guard against malicious overrides of Throwable.equals by 652 // using a Set with identity equality semantics. 653 Set<Throwable> dejaVu = 654 Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>()); 655 dejaVu.add(this); 656 657 synchronized (s.lock()) { 658 // Print our stack trace 659 s.println(this); 660 StackTraceElement[] trace = getOurStackTrace(); 661 for (StackTraceElement traceElement : trace) 662 s.println("\tat " + traceElement); 663 664 // Print suppressed exceptions, if any 665 for (Throwable se : getSuppressed()) 666 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu); 667 668 // Print cause, if any 669 Throwable ourCause = getCause(); 670 if (ourCause != null) 671 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu); 672 } 673 } 674 675 /** 676 * Print our stack trace as an enclosed exception for the specified 677 * stack trace. 678 */ 679 private void printEnclosedStackTrace(PrintStreamOrWriter s, 680 StackTraceElement[] enclosingTrace, 681 String caption, 682 String prefix, 683 Set<Throwable> dejaVu) { 684 assert Thread.holdsLock(s.lock()); 685 if (dejaVu.contains(this)) { 686 s.println("\t[CIRCULAR REFERENCE:" + this + "]"); 687 } else { 688 dejaVu.add(this); 689 // Compute number of frames in common between this and enclosing trace 690 StackTraceElement[] trace = getOurStackTrace(); 691 int m = trace.length - 1; 692 int n = enclosingTrace.length - 1; 693 while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) { 694 m--; n--; 695 } 696 int framesInCommon = trace.length - 1 - m; 697 698 // Print our stack trace 699 s.println(prefix + caption + this); 700 for (int i = 0; i <= m; i++) 701 s.println(prefix + "\tat " + trace[i]); 702 if (framesInCommon != 0) 703 s.println(prefix + "\t... " + framesInCommon + " more"); 704 705 // Print suppressed exceptions, if any 706 for (Throwable se : getSuppressed()) 707 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, 708 prefix +"\t", dejaVu); 709 710 // Print cause, if any 711 Throwable ourCause = getCause(); 712 if (ourCause != null) 713 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu); 714 } 715 } 716 717 /** 718 * Prints this throwable and its backtrace to the specified 719 * print writer. 720 * 721 * @param s {@code PrintWriter} to use for output 722 * @since JDK1.1 723 */ 724 public void printStackTrace(PrintWriter s) { 725 printStackTrace(new WrappedPrintWriter(s)); 726 } 727 728 /** 729 * Wrapper class for PrintStream and PrintWriter to enable a single 730 * implementation of printStackTrace. 731 */ 732 private abstract static class PrintStreamOrWriter { 733 /** Returns the object to be locked when using this StreamOrWriter */ 734 abstract Object lock(); 735 736 /** Prints the specified string as a line on this StreamOrWriter */ 737 abstract void println(Object o); 738 } 739 740 private static class WrappedPrintStream extends PrintStreamOrWriter { 741 private final PrintStream printStream; 742 743 WrappedPrintStream(PrintStream printStream) { 744 this.printStream = printStream; 745 } 746 747 Object lock() { 748 return printStream; 749 } 750 751 void println(Object o) { 752 printStream.println(o); 753 } 754 } 755 756 private static class WrappedPrintWriter extends PrintStreamOrWriter { 757 private final PrintWriter printWriter; 758 759 WrappedPrintWriter(PrintWriter printWriter) { 760 this.printWriter = printWriter; 761 } 762 763 Object lock() { 764 return printWriter; 765 } 766 767 void println(Object o) { 768 printWriter.println(o); 769 } 770 } 771 772 /** 773 * Fills in the execution stack trace. This method records within this 774 * {@code Throwable} object information about the current state of 775 * the stack frames for the current thread. 776 * 777 * <p>If the stack trace of this {@code Throwable} {@linkplain 778 * Throwable#Throwable(String, Throwable, boolean, boolean) is not 779 * writable}, calling this method has no effect. 780 * 781 * @return a reference to this {@code Throwable} instance. 782 * @see java.lang.Throwable#printStackTrace() 783 */ 784 public synchronized Throwable fillInStackTrace() { 785 if (stackTrace != null || 786 backtrace != null /* Out of protocol state */ ) { 787 fillInStackTrace(0); 788 stackTrace = UNASSIGNED_STACK; 789 } 790 return this; 791 } 792 793 private native Throwable fillInStackTrace(int dummy); 794 795 /** 796 * Provides programmatic access to the stack trace information printed by 797 * {@link #printStackTrace()}. Returns an array of stack trace elements, 798 * each representing one stack frame. The zeroth element of the array 799 * (assuming the array's length is non-zero) represents the top of the 800 * stack, which is the last method invocation in the sequence. Typically, 801 * this is the point at which this throwable was created and thrown. 802 * The last element of the array (assuming the array's length is non-zero) 803 * represents the bottom of the stack, which is the first method invocation 804 * in the sequence. 805 * 806 * <p>Some virtual machines may, under some circumstances, omit one 807 * or more stack frames from the stack trace. In the extreme case, 808 * a virtual machine that has no stack trace information concerning 809 * this throwable is permitted to return a zero-length array from this 810 * method. Generally speaking, the array returned by this method will 811 * contain one element for every frame that would be printed by 812 * {@code printStackTrace}. Writes to the returned array do not 813 * affect future calls to this method. 814 * 815 * @return an array of stack trace elements representing the stack trace 816 * pertaining to this throwable. 817 * @since 1.4 818 */ 819 public StackTraceElement[] getStackTrace() { 820 return getOurStackTrace().clone(); 821 } 822 823 private synchronized StackTraceElement[] getOurStackTrace() { 824 // Initialize stack trace field with information from 825 // backtrace if this is the first call to this method 826 if (stackTrace == UNASSIGNED_STACK || 827 (stackTrace == null && backtrace != null) /* Out of protocol state */) { 828 int depth = getStackTraceDepth(); 829 stackTrace = new StackTraceElement[depth]; 830 for (int i=0; i < depth; i++) 831 stackTrace[i] = getStackTraceElement(i); 832 } else if (stackTrace == null) { 833 return UNASSIGNED_STACK; 834 } 835 return stackTrace; 836 } 837 838 /** 839 * Sets the stack trace elements that will be returned by 840 * {@link #getStackTrace()} and printed by {@link #printStackTrace()} 841 * and related methods. 842 * 843 * This method, which is designed for use by RPC frameworks and other 844 * advanced systems, allows the client to override the default 845 * stack trace that is either generated by {@link #fillInStackTrace()} 846 * when a throwable is constructed or deserialized when a throwable is 847 * read from a serialization stream. 848 * 849 * <p>If the stack trace of this {@code Throwable} {@linkplain 850 * Throwable#Throwable(String, Throwable, boolean, boolean) is not 851 * writable}, calling this method has no effect other than 852 * validating its argument. 853 * 854 * @param stackTrace the stack trace elements to be associated with 855 * this {@code Throwable}. The specified array is copied by this 856 * call; changes in the specified array after the method invocation 857 * returns will have no affect on this {@code Throwable}'s stack 858 * trace. 859 * 860 * @throws NullPointerException if {@code stackTrace} is 861 * {@code null} or if any of the elements of 862 * {@code stackTrace} are {@code null} 863 * 864 * @since 1.4 865 */ 866 public void setStackTrace(StackTraceElement[] stackTrace) { 867 // Validate argument 868 StackTraceElement[] defensiveCopy = stackTrace.clone(); 869 for (int i = 0; i < defensiveCopy.length; i++) { 870 if (defensiveCopy[i] == null) 871 throw new NullPointerException("stackTrace[" + i + "]"); 872 } 873 874 synchronized (this) { 875 if (this.stackTrace == null && // Immutable stack 876 backtrace == null) // Test for out of protocol state 877 return; 878 this.stackTrace = defensiveCopy; 879 } 880 } 881 882 /** 883 * Returns the number of elements in the stack trace (or 0 if the stack 884 * trace is unavailable). 885 * 886 * package-protection for use by SharedSecrets. 887 */ 888 native int getStackTraceDepth(); 889 890 /** 891 * Returns the specified element of the stack trace. 892 * 893 * package-protection for use by SharedSecrets. 894 * 895 * @param index index of the element to return. 896 * @throws IndexOutOfBoundsException if {@code index < 0 || 897 * index >= getStackTraceDepth() } 898 */ 899 native StackTraceElement getStackTraceElement(int index); 900 901 /** 902 * Reads a {@code Throwable} from a stream, enforcing 903 * well-formedness constraints on fields. Null entries and 904 * self-pointers are not allowed in the list of {@code 905 * suppressedExceptions}. Null entries are not allowed for stack 906 * trace elements. A null stack trace in the serial form results 907 * in a zero-length stack element array. A single-element stack 908 * trace whose entry is equal to {@code new StackTraceElement("", 909 * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code 910 * stackTrace} field. 911 * 912 * Note that there are no constraints on the value the {@code 913 * cause} field can hold; both {@code null} and {@code this} are 914 * valid values for the field. 915 */ 916 private void readObject(ObjectInputStream s) 917 throws IOException, ClassNotFoundException { 918 s.defaultReadObject(); // read in all fields 919 if (suppressedExceptions != null) { 920 List<Throwable> suppressed = null; 921 if (suppressedExceptions.isEmpty()) { 922 // Use the sentinel for a zero-length list 923 suppressed = SUPPRESSED_SENTINEL; 924 } else { // Copy Throwables to new list 925 suppressed = new ArrayList<>(1); 926 for (Throwable t : suppressedExceptions) { 927 // Enforce constraints on suppressed exceptions in 928 // case of corrupt or malicious stream. 929 if (t == null) 930 throw new NullPointerException(NULL_CAUSE_MESSAGE); 931 if (t == this) 932 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); 933 suppressed.add(t); 934 } 935 } 936 suppressedExceptions = suppressed; 937 } // else a null suppressedExceptions field remains null 938 939 /* 940 * For zero-length stack traces, use a clone of 941 * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to 942 * allow identity comparison against UNASSIGNED_STACK in 943 * getOurStackTrace. The identity of UNASSIGNED_STACK in 944 * stackTrace indicates to the getOurStackTrace method that 945 * the stackTrace needs to be constructed from the information 946 * in backtrace. 947 */ 948 if (stackTrace != null) { 949 if (stackTrace.length == 0) { 950 stackTrace = UNASSIGNED_STACK.clone(); 951 } else if (stackTrace.length == 1 && 952 // Check for the marker of an immutable stack trace 953 SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) { 954 stackTrace = null; 955 } else { // Verify stack trace elements are non-null. 956 for(StackTraceElement ste : stackTrace) { 957 if (ste == null) 958 throw new NullPointerException("null StackTraceElement in serial stream. "); 959 } 960 } 961 } else { 962 // A null stackTrace field in the serial form can result 963 // from an exception serialized without that field in 964 // older JDK releases; treat such exceptions as having 965 // empty stack traces. 966 stackTrace = UNASSIGNED_STACK.clone(); 967 } 968 } 969 970 /** 971 * Write a {@code Throwable} object to a stream. 972 * 973 * A {@code null} stack trace field is represented in the serial 974 * form as a one-element array whose element is equal to {@code 975 * new StackTraceElement("", "", null, Integer.MIN_VALUE)}. 976 */ 977 private synchronized void writeObject(ObjectOutputStream s) 978 throws IOException { 979 // Ensure that the stackTrace field is initialized to a 980 // non-null value, if appropriate. As of JDK 7, a null stack 981 // trace field is a valid value indicating the stack trace 982 // should not be set. 983 getOurStackTrace(); 984 985 StackTraceElement[] oldStackTrace = stackTrace; 986 try { 987 if (stackTrace == null) 988 stackTrace = SentinelHolder.STACK_TRACE_SENTINEL; 989 s.defaultWriteObject(); 990 } finally { 991 stackTrace = oldStackTrace; 992 } 993 } 994 995 /** 996 * Appends the specified exception to the exceptions that were 997 * suppressed in order to deliver this exception. This method is 998 * thread-safe and typically called (automatically and implicitly) 999 * by the {@code try}-with-resources statement. 1000 * 1001 * <p>The suppression behavior is enabled <em>unless</em> disabled 1002 * {@linkplain #Throwable(String, Throwable, boolean, boolean) via 1003 * a constructor}. When suppression is disabled, this method does 1004 * nothing other than to validate its argument. 1005 * 1006 * <p>Note that when one exception {@linkplain 1007 * #initCause(Throwable) causes} another exception, the first 1008 * exception is usually caught and then the second exception is 1009 * thrown in response. In other words, there is a causal 1010 * connection between the two exceptions. 1011 * 1012 * In contrast, there are situations where two independent 1013 * exceptions can be thrown in sibling code blocks, in particular 1014 * in the {@code try} block of a {@code try}-with-resources 1015 * statement and the compiler-generated {@code finally} block 1016 * which closes the resource. 1017 * 1018 * In these situations, only one of the thrown exceptions can be 1019 * propagated. In the {@code try}-with-resources statement, when 1020 * there are two such exceptions, the exception originating from 1021 * the {@code try} block is propagated and the exception from the 1022 * {@code finally} block is added to the list of exceptions 1023 * suppressed by the exception from the {@code try} block. As an 1024 * exception unwinds the stack, it can accumulate multiple 1025 * suppressed exceptions. 1026 * 1027 * <p>An exception may have suppressed exceptions while also being 1028 * caused by another exception. Whether or not an exception has a 1029 * cause is semantically known at the time of its creation, unlike 1030 * whether or not an exception will suppress other exceptions 1031 * which is typically only determined after an exception is 1032 * thrown. 1033 * 1034 * <p>Note that programmer written code is also able to take 1035 * advantage of calling this method in situations where there are 1036 * multiple sibling exceptions and only one can be propagated. 1037 * 1038 * @param exception the exception to be added to the list of 1039 * suppressed exceptions 1040 * @throws IllegalArgumentException if {@code exception} is this 1041 * throwable; a throwable cannot suppress itself. 1042 * @throws NullPointerException if {@code exception} is {@code null} 1043 * @since 1.7 1044 */ 1045 public final synchronized void addSuppressed(Throwable exception) { 1046 if (exception == this) 1047 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception); 1048 1049 if (exception == null) 1050 throw new NullPointerException(NULL_CAUSE_MESSAGE); 1051 1052 if (suppressedExceptions == null) // Suppressed exceptions not recorded 1053 return; 1054 1055 if (suppressedExceptions == SUPPRESSED_SENTINEL) 1056 suppressedExceptions = new ArrayList<>(1); 1057 1058 suppressedExceptions.add(exception); 1059 } 1060 1061 private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0]; 1062 1063 /** 1064 * Returns an array containing all of the exceptions that were 1065 * suppressed, typically by the {@code try}-with-resources 1066 * statement, in order to deliver this exception. 1067 * 1068 * If no exceptions were suppressed or {@linkplain 1069 * #Throwable(String, Throwable, boolean, boolean) suppression is 1070 * disabled}, an empty array is returned. This method is 1071 * thread-safe. Writes to the returned array do not affect future 1072 * calls to this method. 1073 * 1074 * @return an array containing all of the exceptions that were 1075 * suppressed to deliver this exception. 1076 * @since 1.7 1077 */ 1078 public final synchronized Throwable[] getSuppressed() { 1079 if (suppressedExceptions == SUPPRESSED_SENTINEL || 1080 suppressedExceptions == null) 1081 return EMPTY_THROWABLE_ARRAY; 1082 else 1083 return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY); 1084 } 1085 }