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