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