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