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