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