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