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