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