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