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