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