0N/A/*
6141N/A * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.lang;
0N/Aimport java.io.*;
2548N/Aimport java.util.*;
0N/A
0N/A/**
2607N/A * The {@code Throwable} class is the superclass of all errors and
0N/A * exceptions in the Java language. Only objects that are instances of this
0N/A * class (or one of its subclasses) are thrown by the Java Virtual Machine or
2607N/A * can be thrown by the Java {@code throw} statement. Similarly, only
0N/A * this class or one of its subclasses can be the argument type in a
2607N/A * {@code catch} clause.
0N/A *
2081N/A * For the purposes of compile-time checking of exceptions, {@code
2081N/A * Throwable} and any subclass of {@code Throwable} that is not also a
2081N/A * subclass of either {@link RuntimeException} or {@link Error} are
2081N/A * regarded as checked exceptions.
2081N/A *
0N/A * <p>Instances of two subclasses, {@link java.lang.Error} and
0N/A * {@link java.lang.Exception}, are conventionally used to indicate
0N/A * that exceptional situations have occurred. Typically, these instances
0N/A * are freshly created in the context of the exceptional situation so
0N/A * as to include relevant information (such as stack trace data).
0N/A *
3879N/A * <p>A throwable contains a snapshot of the execution stack of its
3879N/A * thread at the time it was created. It can also contain a message
3879N/A * string that gives more information about the error. Over time, a
3879N/A * throwable can {@linkplain Throwable#addSuppressed suppress} other
3879N/A * throwables from being propagated. Finally, the throwable can also
3879N/A * contain a <i>cause</i>: another throwable that caused this
3894N/A * throwable to be constructed. The recording of this causal information
3879N/A * is referred to as the <i>chained exception</i> facility, as the
3879N/A * cause can, itself, have a cause, and so on, leading to a "chain" of
3879N/A * exceptions, each caused by another.
0N/A *
0N/A * <p>One reason that a throwable may have a cause is that the class that
0N/A * throws it is built atop a lower layered abstraction, and an operation on
0N/A * the upper layer fails due to a failure in the lower layer. It would be bad
0N/A * design to let the throwable thrown by the lower layer propagate outward, as
0N/A * it is generally unrelated to the abstraction provided by the upper layer.
0N/A * Further, doing so would tie the API of the upper layer to the details of
0N/A * its implementation, assuming the lower layer's exception was a checked
0N/A * exception. Throwing a "wrapped exception" (i.e., an exception containing a
0N/A * cause) allows the upper layer to communicate the details of the failure to
0N/A * its caller without incurring either of these shortcomings. It preserves
0N/A * the flexibility to change the implementation of the upper layer without
0N/A * changing its API (in particular, the set of exceptions thrown by its
0N/A * methods).
0N/A *
0N/A * <p>A second reason that a throwable may have a cause is that the method
0N/A * that throws it must conform to a general-purpose interface that does not
0N/A * permit the method to throw the cause directly. For example, suppose
0N/A * a persistent collection conforms to the {@link java.util.Collection
0N/A * Collection} interface, and that its persistence is implemented atop
2607N/A * {@code java.io}. Suppose the internals of the {@code add} method
0N/A * can throw an {@link java.io.IOException IOException}. The implementation
2607N/A * can communicate the details of the {@code IOException} to its caller
2607N/A * while conforming to the {@code Collection} interface by wrapping the
2607N/A * {@code IOException} in an appropriate unchecked exception. (The
0N/A * specification for the persistent collection should indicate that it is
0N/A * capable of throwing such exceptions.)
0N/A *
0N/A * <p>A cause can be associated with a throwable in two ways: via a
0N/A * constructor that takes the cause as an argument, or via the
0N/A * {@link #initCause(Throwable)} method. New throwable classes that
0N/A * wish to allow causes to be associated with them should provide constructors
0N/A * that take a cause and delegate (perhaps indirectly) to one of the
3879N/A * {@code Throwable} constructors that takes a cause.
3879N/A *
2607N/A * Because the {@code initCause} method is public, it allows a cause to be
0N/A * associated with any throwable, even a "legacy throwable" whose
0N/A * implementation predates the addition of the exception chaining mechanism to
3879N/A * {@code Throwable}.
0N/A *
2607N/A * <p>By convention, class {@code Throwable} and its subclasses have two
0N/A * constructors, one that takes no arguments and one that takes a
2607N/A * {@code String} argument that can be used to produce a detail message.
0N/A * Further, those subclasses that might likely have a cause associated with
0N/A * them should have two more constructors, one that takes a
2607N/A * {@code Throwable} (the cause), and one that takes a
2607N/A * {@code String} (the detail message) and a {@code Throwable} (the
0N/A * cause).
0N/A *
0N/A * @author unascribed
0N/A * @author Josh Bloch (Added exception chaining and programmatic access to
0N/A * stack trace in 1.4.)
4008N/A * @jls 11.2 Compile-Time Checking of Exceptions
0N/A * @since JDK1.0
0N/A */
0N/Apublic class Throwable implements Serializable {
0N/A /** use serialVersionUID from JDK 1.0.2 for interoperability */
0N/A private static final long serialVersionUID = -3042686055658047285L;
0N/A
0N/A /**
0N/A * Native code saves some indication of the stack backtrace in this slot.
0N/A */
0N/A private transient Object backtrace;
0N/A
0N/A /**
0N/A * Specific details about the Throwable. For example, for
2607N/A * {@code FileNotFoundException}, this contains the name of
0N/A * the file that could not be found.
0N/A *
0N/A * @serial
0N/A */
0N/A private String detailMessage;
0N/A
4116N/A
4116N/A /**
4116N/A * Holder class to defer initializing sentinel objects only used
4116N/A * for serialization.
4116N/A */
4116N/A private static class SentinelHolder {
4116N/A /**
4116N/A * {@linkplain #setStackTrace(StackTraceElement[]) Setting the
4116N/A * stack trace} to a one-element array containing this sentinel
4116N/A * value indicates future attempts to set the stack trace will be
4116N/A * ignored. The sentinal is equal to the result of calling:<br>
4116N/A * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
4116N/A */
4116N/A public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
4116N/A new StackTraceElement("", "", null, Integer.MIN_VALUE);
4116N/A
4116N/A /**
4116N/A * Sentinel value used in the serial form to indicate an immutable
4116N/A * stack trace.
4116N/A */
4116N/A public static final StackTraceElement[] STACK_TRACE_SENTINEL =
4116N/A new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
4116N/A }
4116N/A
0N/A /**
3057N/A * A shared value for an empty stack.
3057N/A */
4116N/A private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];
3057N/A
3057N/A /*
3057N/A * To allow Throwable objects to be made immutable and safely
3057N/A * reused by the JVM, such as OutOfMemoryErrors, fields of
4116N/A * Throwable that are writable in response to user actions, cause,
4116N/A * stackTrace, and suppressedExceptions obey the following
4116N/A * protocol:
3057N/A *
3057N/A * 1) The fields are initialized to a non-null sentinel value
3057N/A * which indicates the value has logically not been set.
3057N/A *
3057N/A * 2) Writing a null to the field indicates further writes
3057N/A * are forbidden
3057N/A *
3057N/A * 3) The sentinel value may be replaced with another non-null
3057N/A * value.
3057N/A *
3057N/A * For example, implementations of the HotSpot JVM have
3057N/A * preallocated OutOfMemoryError objects to provide for better
3057N/A * diagnosability of that situation. These objects are created
3057N/A * without calling the constructor for that class and the fields
3057N/A * in question are initialized to null. To support this
3057N/A * capability, any new fields added to Throwable that require
3057N/A * being initialized to a non-null value require a coordinated JVM
3057N/A * change.
3057N/A */
3057N/A
3057N/A /**
0N/A * The throwable that caused this throwable to get thrown, or null if this
0N/A * throwable was not caused by another throwable, or if the causative
0N/A * throwable is unknown. If this field is equal to this throwable itself,
0N/A * it indicates that the cause of this throwable has not yet been
0N/A * initialized.
0N/A *
0N/A * @serial
0N/A * @since 1.4
0N/A */
0N/A private Throwable cause = this;
0N/A
0N/A /**
0N/A * The stack trace, as returned by {@link #getStackTrace()}.
0N/A *
4116N/A * The field is initialized to a zero-length array. A {@code
4116N/A * null} value of this field indicates subsequent calls to {@link
4116N/A * #setStackTrace(StackTraceElement[])} and {@link
4116N/A * #fillInStackTrace()} will be be no-ops.
4116N/A *
0N/A * @serial
0N/A * @since 1.4
0N/A */
4116N/A private StackTraceElement[] stackTrace = UNASSIGNED_STACK;
3057N/A
3057N/A // Setting this static field introduces an acceptable
3057N/A // initialization dependency on a few java.util classes.
3057N/A private static final List<Throwable> SUPPRESSED_SENTINEL =
3057N/A Collections.unmodifiableList(new ArrayList<Throwable>(0));
0N/A
0N/A /**
3057N/A * The list of suppressed exceptions, as returned by {@link
3057N/A * #getSuppressed()}. The list is initialized to a zero-element
3057N/A * unmodifiable sentinel list. When a serialized Throwable is
3057N/A * read in, if the {@code suppressedExceptions} field points to a
3057N/A * zero-element list, the field is reset to the sentinel value.
2548N/A *
2548N/A * @serial
2548N/A * @since 1.7
2548N/A */
3057N/A private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
2548N/A
2548N/A /** Message for trying to suppress a null exception. */
2548N/A private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
2548N/A
3057N/A /** Message for trying to suppress oneself. */
3057N/A private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
3057N/A
2548N/A /** Caption for labeling causative exception stack traces */
2548N/A private static final String CAUSE_CAPTION = "Caused by: ";
2548N/A
2548N/A /** Caption for labeling suppressed exception stack traces */
2548N/A private static final String SUPPRESSED_CAPTION = "Suppressed: ";
2548N/A
2548N/A /**
2607N/A * Constructs a new throwable with {@code null} as its detail message.
0N/A * The cause is not initialized, and may subsequently be initialized by a
0N/A * call to {@link #initCause}.
0N/A *
0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize
0N/A * the stack trace data in the newly created throwable.
0N/A */
0N/A public Throwable() {
0N/A fillInStackTrace();
0N/A }
0N/A
0N/A /**
0N/A * Constructs a new throwable with the specified detail message. The
0N/A * cause is not initialized, and may subsequently be initialized by
0N/A * a call to {@link #initCause}.
0N/A *
0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize
0N/A * the stack trace data in the newly created throwable.
0N/A *
0N/A * @param message the detail message. The detail message is saved for
0N/A * later retrieval by the {@link #getMessage()} method.
0N/A */
0N/A public Throwable(String message) {
0N/A fillInStackTrace();
0N/A detailMessage = message;
0N/A }
0N/A
0N/A /**
0N/A * Constructs a new throwable with the specified detail message and
0N/A * cause. <p>Note that the detail message associated with
2607N/A * {@code cause} is <i>not</i> automatically incorporated in
0N/A * this throwable's detail message.
0N/A *
0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize
0N/A * the stack trace data in the newly created throwable.
0N/A *
0N/A * @param message the detail message (which is saved for later retrieval
0N/A * by the {@link #getMessage()} method).
0N/A * @param cause the cause (which is saved for later retrieval by the
2607N/A * {@link #getCause()} method). (A {@code null} value is
0N/A * permitted, and indicates that the cause is nonexistent or
0N/A * unknown.)
0N/A * @since 1.4
0N/A */
0N/A public Throwable(String message, Throwable cause) {
0N/A fillInStackTrace();
0N/A detailMessage = message;
0N/A this.cause = cause;
0N/A }
0N/A
0N/A /**
0N/A * Constructs a new throwable with the specified cause and a detail
2607N/A * message of {@code (cause==null ? null : cause.toString())} (which
2607N/A * typically contains the class and detail message of {@code cause}).
0N/A * This constructor is useful for throwables that are little more than
0N/A * wrappers for other throwables (for example, {@link
0N/A * java.security.PrivilegedActionException}).
0N/A *
0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize
0N/A * the stack trace data in the newly created throwable.
0N/A *
0N/A * @param cause the cause (which is saved for later retrieval by the
2607N/A * {@link #getCause()} method). (A {@code null} value is
0N/A * permitted, and indicates that the cause is nonexistent or
0N/A * unknown.)
0N/A * @since 1.4
0N/A */
0N/A public Throwable(Throwable cause) {
0N/A fillInStackTrace();
0N/A detailMessage = (cause==null ? null : cause.toString());
0N/A this.cause = cause;
0N/A }
0N/A
0N/A /**
3894N/A * Constructs a new throwable with the specified detail message,
4116N/A * cause, {@linkplain #addSuppressed suppression} enabled or
4116N/A * disabled, and writable stack trace enabled or disabled. If
4116N/A * suppression is disabled, {@link #getSuppressed} for this object
4116N/A * will return a zero-length array and calls to {@link
4116N/A * #addSuppressed} that would otherwise append an exception to the
4116N/A * suppressed list will have no effect. If the writable stack
4116N/A * trace is false, this constructor will not call {@link
4116N/A * #fillInStackTrace()}, a {@code null} will be written to the
4116N/A * {@code stackTrace} field, and subsequent calls to {@code
4116N/A * fillInStackTrace} and {@link
4116N/A * #setStackTrace(StackTraceElement[])} will not set the stack
4116N/A * trace. If the writable stack trace is false, {@link
4116N/A * #getStackTrace} will return a zero length array.
3894N/A *
3894N/A * <p>Note that the other constructors of {@code Throwable} treat
4116N/A * suppression as being enabled and the stack trace as being
4116N/A * writable. Subclasses of {@code Throwable} should document any
4116N/A * conditions under which suppression is disabled and document
4116N/A * conditions under which the stack trace is not writable.
4116N/A * Disabling of suppression should only occur in exceptional
4116N/A * circumstances where special requirements exist, such as a
4116N/A * virtual machine reusing exception objects under low-memory
4220N/A * situations. Circumstances where a given exception object is
4220N/A * repeatedly caught and rethrown, such as to implement control
4220N/A * flow between two sub-systems, is another situation where
4220N/A * immutable throwable objects would be appropriate.
3894N/A *
3894N/A * @param message the detail message.
3894N/A * @param cause the cause. (A {@code null} value is permitted,
3894N/A * and indicates that the cause is nonexistent or unknown.)
3894N/A * @param enableSuppression whether or not suppression is enabled or disabled
4116N/A * @param writableStackTrace whether or not the stack trace should be
4116N/A * writable
3894N/A *
3894N/A * @see OutOfMemoryError
3894N/A * @see NullPointerException
3894N/A * @see ArithmeticException
3894N/A * @since 1.7
3894N/A */
3894N/A protected Throwable(String message, Throwable cause,
4116N/A boolean enableSuppression,
4116N/A boolean writableStackTrace) {
4116N/A if (writableStackTrace) {
4116N/A fillInStackTrace();
4116N/A } else {
4116N/A stackTrace = null;
4116N/A }
3894N/A detailMessage = message;
3894N/A this.cause = cause;
3894N/A if (!enableSuppression)
3894N/A suppressedExceptions = null;
3894N/A }
3894N/A
3894N/A /**
0N/A * Returns the detail message string of this throwable.
0N/A *
2607N/A * @return the detail message string of this {@code Throwable} instance
2607N/A * (which may be {@code null}).
0N/A */
0N/A public String getMessage() {
0N/A return detailMessage;
0N/A }
0N/A
0N/A /**
0N/A * Creates a localized description of this throwable.
0N/A * Subclasses may override this method in order to produce a
0N/A * locale-specific message. For subclasses that do not override this
0N/A * method, the default implementation returns the same result as
2607N/A * {@code getMessage()}.
0N/A *
0N/A * @return The localized description of this throwable.
0N/A * @since JDK1.1
0N/A */
0N/A public String getLocalizedMessage() {
0N/A return getMessage();
0N/A }
0N/A
0N/A /**
2607N/A * Returns the cause of this throwable or {@code null} if the
0N/A * cause is nonexistent or unknown. (The cause is the throwable that
0N/A * caused this throwable to get thrown.)
0N/A *
0N/A * <p>This implementation returns the cause that was supplied via one of
2607N/A * the constructors requiring a {@code Throwable}, or that was set after
0N/A * creation with the {@link #initCause(Throwable)} method. While it is
0N/A * typically unnecessary to override this method, a subclass can override
0N/A * it to return a cause set by some other means. This is appropriate for
0N/A * a "legacy chained throwable" that predates the addition of chained
2607N/A * exceptions to {@code Throwable}. Note that it is <i>not</i>
2607N/A * necessary to override any of the {@code PrintStackTrace} methods,
2607N/A * all of which invoke the {@code getCause} method to determine the
0N/A * cause of a throwable.
0N/A *
2607N/A * @return the cause of this throwable or {@code null} if the
0N/A * cause is nonexistent or unknown.
0N/A * @since 1.4
0N/A */
2656N/A public synchronized Throwable getCause() {
0N/A return (cause==this ? null : cause);
0N/A }
0N/A
0N/A /**
0N/A * Initializes the <i>cause</i> of this throwable to the specified value.
0N/A * (The cause is the throwable that caused this throwable to get thrown.)
0N/A *
0N/A * <p>This method can be called at most once. It is generally called from
0N/A * within the constructor, or immediately after creating the
0N/A * throwable. If this throwable was created
0N/A * with {@link #Throwable(Throwable)} or
0N/A * {@link #Throwable(String,Throwable)}, this method cannot be called
0N/A * even once.
0N/A *
4220N/A * <p>An example of using this method on a legacy throwable type
4220N/A * without other support for setting the cause is:
4220N/A *
4220N/A * <pre>
4220N/A * try {
4220N/A * lowLevelOp();
4220N/A * } catch (LowLevelException le) {
4220N/A * throw (HighLevelException)
4220N/A * new HighLevelException().initCause(le); // Legacy constructor
4220N/A * }
4220N/A * </pre>
4220N/A *
0N/A * @param cause the cause (which is saved for later retrieval by the
2607N/A * {@link #getCause()} method). (A {@code null} value is
0N/A * permitted, and indicates that the cause is nonexistent or
0N/A * unknown.)
2607N/A * @return a reference to this {@code Throwable} instance.
2607N/A * @throws IllegalArgumentException if {@code cause} is this
0N/A * throwable. (A throwable cannot be its own cause.)
0N/A * @throws IllegalStateException if this throwable was
0N/A * created with {@link #Throwable(Throwable)} or
0N/A * {@link #Throwable(String,Throwable)}, or this method has already
0N/A * been called on this throwable.
0N/A * @since 1.4
0N/A */
0N/A public synchronized Throwable initCause(Throwable cause) {
0N/A if (this.cause != this)
6141N/A throw new IllegalStateException("Can't overwrite cause with " +
6141N/A Objects.toString(cause, "a null"), this);
0N/A if (cause == this)
6141N/A throw new IllegalArgumentException("Self-causation not permitted", this);
0N/A this.cause = cause;
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Returns a short description of this throwable.
0N/A * The result is the concatenation of:
0N/A * <ul>
0N/A * <li> the {@linkplain Class#getName() name} of the class of this object
0N/A * <li> ": " (a colon and a space)
0N/A * <li> the result of invoking this object's {@link #getLocalizedMessage}
0N/A * method
0N/A * </ul>
2607N/A * If {@code getLocalizedMessage} returns {@code null}, then just
0N/A * the class name is returned.
0N/A *
0N/A * @return a string representation of this throwable.
0N/A */
0N/A public String toString() {
0N/A String s = getClass().getName();
0N/A String message = getLocalizedMessage();
0N/A return (message != null) ? (s + ": " + message) : s;
0N/A }
0N/A
0N/A /**
0N/A * Prints this throwable and its backtrace to the
0N/A * standard error stream. This method prints a stack trace for this
2607N/A * {@code Throwable} object on the error output stream that is
2607N/A * the value of the field {@code System.err}. The first line of
0N/A * output contains the result of the {@link #toString()} method for
0N/A * this object. Remaining lines represent data previously recorded by
0N/A * the method {@link #fillInStackTrace()}. The format of this
0N/A * information depends on the implementation, but the following
0N/A * example may be regarded as typical:
0N/A * <blockquote><pre>
0N/A * java.lang.NullPointerException
0N/A * at MyClass.mash(MyClass.java:9)
0N/A * at MyClass.crunch(MyClass.java:6)
0N/A * at MyClass.main(MyClass.java:3)
0N/A * </pre></blockquote>
0N/A * This example was produced by running the program:
0N/A * <pre>
0N/A * class MyClass {
0N/A * public static void main(String[] args) {
0N/A * crunch(null);
0N/A * }
0N/A * static void crunch(int[] a) {
0N/A * mash(a);
0N/A * }
0N/A * static void mash(int[] b) {
0N/A * System.out.println(b[0]);
0N/A * }
0N/A * }
0N/A * </pre>
0N/A * The backtrace for a throwable with an initialized, non-null cause
0N/A * should generally include the backtrace for the cause. The format
0N/A * of this information depends on the implementation, but the following
0N/A * example may be regarded as typical:
0N/A * <pre>
0N/A * HighLevelException: MidLevelException: LowLevelException
0N/A * at Junk.a(Junk.java:13)
0N/A * at Junk.main(Junk.java:4)
0N/A * Caused by: MidLevelException: LowLevelException
0N/A * at Junk.c(Junk.java:23)
0N/A * at Junk.b(Junk.java:17)
0N/A * at Junk.a(Junk.java:11)
0N/A * ... 1 more
0N/A * Caused by: LowLevelException
0N/A * at Junk.e(Junk.java:30)
0N/A * at Junk.d(Junk.java:27)
0N/A * at Junk.c(Junk.java:21)
0N/A * ... 3 more
0N/A * </pre>
2607N/A * Note the presence of lines containing the characters {@code "..."}.
0N/A * These lines indicate that the remainder of the stack trace for this
0N/A * exception matches the indicated number of frames from the bottom of the
0N/A * stack trace of the exception that was caused by this exception (the
0N/A * "enclosing" exception). This shorthand can greatly reduce the length
0N/A * of the output in the common case where a wrapped exception is thrown
0N/A * from same method as the "causative exception" is caught. The above
0N/A * example was produced by running the program:
0N/A * <pre>
0N/A * public class Junk {
0N/A * public static void main(String args[]) {
0N/A * try {
0N/A * a();
0N/A * } catch(HighLevelException e) {
0N/A * e.printStackTrace();
0N/A * }
0N/A * }
0N/A * static void a() throws HighLevelException {
0N/A * try {
0N/A * b();
0N/A * } catch(MidLevelException e) {
0N/A * throw new HighLevelException(e);
0N/A * }
0N/A * }
0N/A * static void b() throws MidLevelException {
0N/A * c();
0N/A * }
0N/A * static void c() throws MidLevelException {
0N/A * try {
0N/A * d();
0N/A * } catch(LowLevelException e) {
0N/A * throw new MidLevelException(e);
0N/A * }
0N/A * }
0N/A * static void d() throws LowLevelException {
0N/A * e();
0N/A * }
0N/A * static void e() throws LowLevelException {
0N/A * throw new LowLevelException();
0N/A * }
0N/A * }
0N/A *
0N/A * class HighLevelException extends Exception {
0N/A * HighLevelException(Throwable cause) { super(cause); }
0N/A * }
0N/A *
0N/A * class MidLevelException extends Exception {
0N/A * MidLevelException(Throwable cause) { super(cause); }
0N/A * }
0N/A *
0N/A * class LowLevelException extends Exception {
0N/A * }
0N/A * </pre>
2548N/A * As of release 7, the platform supports the notion of
2726N/A * <i>suppressed exceptions</i> (in conjunction with the {@code
2726N/A * try}-with-resources statement). Any exceptions that were
2548N/A * suppressed in order to deliver an exception are printed out
2548N/A * beneath the stack trace. The format of this information
2548N/A * depends on the implementation, but the following example may be
2548N/A * regarded as typical:
2548N/A *
2548N/A * <pre>
2548N/A * Exception in thread "main" java.lang.Exception: Something happened
2548N/A * at Foo.bar(Foo.java:10)
2548N/A * at Foo.main(Foo.java:5)
2548N/A * Suppressed: Resource$CloseFailException: Resource ID = 0
2548N/A * at Resource.close(Resource.java:26)
2548N/A * at Foo.bar(Foo.java:9)
2548N/A * ... 1 more
2548N/A * </pre>
2548N/A * Note that the "... n more" notation is used on suppressed exceptions
2548N/A * just at it is used on causes. Unlike causes, suppressed exceptions are
2548N/A * indented beyond their "containing exceptions."
2548N/A *
2548N/A * <p>An exception can have both a cause and one or more suppressed
2548N/A * exceptions:
2548N/A * <pre>
2548N/A * Exception in thread "main" java.lang.Exception: Main block
2548N/A * at Foo3.main(Foo3.java:7)
2548N/A * Suppressed: Resource$CloseFailException: Resource ID = 2
2548N/A * at Resource.close(Resource.java:26)
2548N/A * at Foo3.main(Foo3.java:5)
2548N/A * Suppressed: Resource$CloseFailException: Resource ID = 1
2548N/A * at Resource.close(Resource.java:26)
2548N/A * at Foo3.main(Foo3.java:5)
2548N/A * Caused by: java.lang.Exception: I did it
2548N/A * at Foo3.main(Foo3.java:8)
2548N/A * </pre>
2548N/A * Likewise, a suppressed exception can have a cause:
2548N/A * <pre>
2548N/A * Exception in thread "main" java.lang.Exception: Main block
2548N/A * at Foo4.main(Foo4.java:6)
2548N/A * Suppressed: Resource2$CloseFailException: Resource ID = 1
2548N/A * at Resource2.close(Resource2.java:20)
2548N/A * at Foo4.main(Foo4.java:5)
2548N/A * Caused by: java.lang.Exception: Rats, you caught me
2548N/A * at Resource2$CloseFailException.<init>(Resource2.java:45)
2548N/A * ... 2 more
2548N/A * </pre>
0N/A */
0N/A public void printStackTrace() {
0N/A printStackTrace(System.err);
0N/A }
0N/A
0N/A /**
0N/A * Prints this throwable and its backtrace to the specified print stream.
0N/A *
2607N/A * @param s {@code PrintStream} to use for output
0N/A */
0N/A public void printStackTrace(PrintStream s) {
2548N/A printStackTrace(new WrappedPrintStream(s));
2548N/A }
2548N/A
2548N/A private void printStackTrace(PrintStreamOrWriter s) {
2607N/A // Guard against malicious overrides of Throwable.equals by
2607N/A // using a Set with identity equality semantics.
2607N/A Set<Throwable> dejaVu =
2607N/A Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
2548N/A dejaVu.add(this);
2548N/A
2548N/A synchronized (s.lock()) {
2548N/A // Print our stack trace
0N/A s.println(this);
0N/A StackTraceElement[] trace = getOurStackTrace();
2548N/A for (StackTraceElement traceElement : trace)
2548N/A s.println("\tat " + traceElement);
0N/A
2548N/A // Print suppressed exceptions, if any
3057N/A for (Throwable se : getSuppressed())
2548N/A se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
2548N/A
2548N/A // Print cause, if any
0N/A Throwable ourCause = getCause();
0N/A if (ourCause != null)
2548N/A ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
0N/A }
0N/A }
0N/A
0N/A /**
2548N/A * Print our stack trace as an enclosed exception for the specified
2548N/A * stack trace.
0N/A */
2548N/A private void printEnclosedStackTrace(PrintStreamOrWriter s,
2548N/A StackTraceElement[] enclosingTrace,
2548N/A String caption,
2548N/A String prefix,
2548N/A Set<Throwable> dejaVu) {
2548N/A assert Thread.holdsLock(s.lock());
2548N/A if (dejaVu.contains(this)) {
2548N/A s.println("\t[CIRCULAR REFERENCE:" + this + "]");
2548N/A } else {
2548N/A dejaVu.add(this);
2548N/A // Compute number of frames in common between this and enclosing trace
2548N/A StackTraceElement[] trace = getOurStackTrace();
2548N/A int m = trace.length - 1;
2548N/A int n = enclosingTrace.length - 1;
2548N/A while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
2548N/A m--; n--;
2548N/A }
2548N/A int framesInCommon = trace.length - 1 - m;
0N/A
2548N/A // Print our stack trace
2548N/A s.println(prefix + caption + this);
2548N/A for (int i = 0; i <= m; i++)
2548N/A s.println(prefix + "\tat " + trace[i]);
2548N/A if (framesInCommon != 0)
2548N/A s.println(prefix + "\t... " + framesInCommon + " more");
2548N/A
2548N/A // Print suppressed exceptions, if any
3057N/A for (Throwable se : getSuppressed())
2548N/A se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
2548N/A prefix +"\t", dejaVu);
2548N/A
2548N/A // Print cause, if any
2548N/A Throwable ourCause = getCause();
2548N/A if (ourCause != null)
2548N/A ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Prints this throwable and its backtrace to the specified
0N/A * print writer.
0N/A *
2607N/A * @param s {@code PrintWriter} to use for output
0N/A * @since JDK1.1
0N/A */
0N/A public void printStackTrace(PrintWriter s) {
2548N/A printStackTrace(new WrappedPrintWriter(s));
0N/A }
0N/A
0N/A /**
2548N/A * Wrapper class for PrintStream and PrintWriter to enable a single
2548N/A * implementation of printStackTrace.
0N/A */
2548N/A private abstract static class PrintStreamOrWriter {
2548N/A /** Returns the object to be locked when using this StreamOrWriter */
2548N/A abstract Object lock();
2548N/A
2548N/A /** Prints the specified string as a line on this StreamOrWriter */
2548N/A abstract void println(Object o);
2548N/A }
0N/A
2548N/A private static class WrappedPrintStream extends PrintStreamOrWriter {
2548N/A private final PrintStream printStream;
2548N/A
2548N/A WrappedPrintStream(PrintStream printStream) {
2548N/A this.printStream = printStream;
2548N/A }
2548N/A
2548N/A Object lock() {
2548N/A return printStream;
0N/A }
2548N/A
2548N/A void println(Object o) {
2548N/A printStream.println(o);
2548N/A }
2548N/A }
2548N/A
2548N/A private static class WrappedPrintWriter extends PrintStreamOrWriter {
2548N/A private final PrintWriter printWriter;
0N/A
2548N/A WrappedPrintWriter(PrintWriter printWriter) {
2548N/A this.printWriter = printWriter;
2548N/A }
0N/A
2548N/A Object lock() {
2548N/A return printWriter;
2548N/A }
2548N/A
2548N/A void println(Object o) {
2548N/A printWriter.println(o);
2548N/A }
0N/A }
0N/A
0N/A /**
0N/A * Fills in the execution stack trace. This method records within this
2607N/A * {@code Throwable} object information about the current state of
0N/A * the stack frames for the current thread.
0N/A *
4116N/A * <p>If the stack trace of this {@code Throwable} {@linkplain
4116N/A * Throwable#Throwable(String, Throwable, boolean, boolean) is not
4116N/A * writable}, calling this method has no effect.
4116N/A *
2607N/A * @return a reference to this {@code Throwable} instance.
0N/A * @see java.lang.Throwable#printStackTrace()
0N/A */
4116N/A public synchronized Throwable fillInStackTrace() {
4240N/A if (stackTrace != null ||
4240N/A backtrace != null /* Out of protocol state */ ) {
4116N/A fillInStackTrace(0);
4116N/A stackTrace = UNASSIGNED_STACK;
4116N/A }
4116N/A return this;
4116N/A }
4116N/A
4116N/A private native Throwable fillInStackTrace(int dummy);
0N/A
0N/A /**
0N/A * Provides programmatic access to the stack trace information printed by
0N/A * {@link #printStackTrace()}. Returns an array of stack trace elements,
0N/A * each representing one stack frame. The zeroth element of the array
0N/A * (assuming the array's length is non-zero) represents the top of the
0N/A * stack, which is the last method invocation in the sequence. Typically,
0N/A * this is the point at which this throwable was created and thrown.
0N/A * The last element of the array (assuming the array's length is non-zero)
0N/A * represents the bottom of the stack, which is the first method invocation
0N/A * in the sequence.
0N/A *
0N/A * <p>Some virtual machines may, under some circumstances, omit one
0N/A * or more stack frames from the stack trace. In the extreme case,
0N/A * a virtual machine that has no stack trace information concerning
0N/A * this throwable is permitted to return a zero-length array from this
0N/A * method. Generally speaking, the array returned by this method will
0N/A * contain one element for every frame that would be printed by
4220N/A * {@code printStackTrace}. Writes to the returned array do not
4220N/A * affect future calls to this method.
0N/A *
0N/A * @return an array of stack trace elements representing the stack trace
0N/A * pertaining to this throwable.
0N/A * @since 1.4
0N/A */
0N/A public StackTraceElement[] getStackTrace() {
0N/A return getOurStackTrace().clone();
0N/A }
0N/A
0N/A private synchronized StackTraceElement[] getOurStackTrace() {
4116N/A // Initialize stack trace field with information from
4116N/A // backtrace if this is the first call to this method
4240N/A if (stackTrace == UNASSIGNED_STACK ||
4240N/A (stackTrace == null && backtrace != null) /* Out of protocol state */) {
0N/A int depth = getStackTraceDepth();
0N/A stackTrace = new StackTraceElement[depth];
0N/A for (int i=0; i < depth; i++)
0N/A stackTrace[i] = getStackTraceElement(i);
4116N/A } else if (stackTrace == null) {
4116N/A return UNASSIGNED_STACK;
0N/A }
0N/A return stackTrace;
0N/A }
0N/A
0N/A /**
0N/A * Sets the stack trace elements that will be returned by
0N/A * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
0N/A * and related methods.
0N/A *
0N/A * This method, which is designed for use by RPC frameworks and other
0N/A * advanced systems, allows the client to override the default
0N/A * stack trace that is either generated by {@link #fillInStackTrace()}
0N/A * when a throwable is constructed or deserialized when a throwable is
0N/A * read from a serialization stream.
0N/A *
4116N/A * <p>If the stack trace of this {@code Throwable} {@linkplain
4116N/A * Throwable#Throwable(String, Throwable, boolean, boolean) is not
4116N/A * writable}, calling this method has no effect other than
4116N/A * validating its argument.
4116N/A *
0N/A * @param stackTrace the stack trace elements to be associated with
2607N/A * this {@code Throwable}. The specified array is copied by this
0N/A * call; changes in the specified array after the method invocation
2607N/A * returns will have no affect on this {@code Throwable}'s stack
0N/A * trace.
0N/A *
2607N/A * @throws NullPointerException if {@code stackTrace} is
4116N/A * {@code null} or if any of the elements of
2607N/A * {@code stackTrace} are {@code null}
0N/A *
0N/A * @since 1.4
0N/A */
0N/A public void setStackTrace(StackTraceElement[] stackTrace) {
4116N/A // Validate argument
0N/A StackTraceElement[] defensiveCopy = stackTrace.clone();
4116N/A for (int i = 0; i < defensiveCopy.length; i++) {
0N/A if (defensiveCopy[i] == null)
0N/A throw new NullPointerException("stackTrace[" + i + "]");
4116N/A }
4116N/A
2656N/A synchronized (this) {
4240N/A if (this.stackTrace == null && // Immutable stack
4240N/A backtrace == null) // Test for out of protocol state
4137N/A return;
2656N/A this.stackTrace = defensiveCopy;
2656N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the number of elements in the stack trace (or 0 if the stack
0N/A * trace is unavailable).
1271N/A *
1271N/A * package-protection for use by SharedSecrets.
0N/A */
1271N/A native int getStackTraceDepth();
0N/A
0N/A /**
0N/A * Returns the specified element of the stack trace.
0N/A *
1271N/A * package-protection for use by SharedSecrets.
1271N/A *
0N/A * @param index index of the element to return.
2607N/A * @throws IndexOutOfBoundsException if {@code index < 0 ||
2607N/A * index >= getStackTraceDepth() }
0N/A */
1271N/A native StackTraceElement getStackTraceElement(int index);
0N/A
3057N/A /**
3399N/A * Reads a {@code Throwable} from a stream, enforcing
3057N/A * well-formedness constraints on fields. Null entries and
3057N/A * self-pointers are not allowed in the list of {@code
3057N/A * suppressedExceptions}. Null entries are not allowed for stack
4116N/A * trace elements. A null stack trace in the serial form results
4116N/A * in a zero-length stack element array. A single-element stack
4116N/A * trace whose entry is equal to {@code new StackTraceElement("",
4116N/A * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
4116N/A * stackTrace} field.
3057N/A *
3057N/A * Note that there are no constraints on the value the {@code
3057N/A * cause} field can hold; both {@code null} and {@code this} are
3057N/A * valid values for the field.
3057N/A */
2548N/A private void readObject(ObjectInputStream s)
2548N/A throws IOException, ClassNotFoundException {
2548N/A s.defaultReadObject(); // read in all fields
3057N/A if (suppressedExceptions != null) {
3057N/A List<Throwable> suppressed = null;
3057N/A if (suppressedExceptions.isEmpty()) {
3057N/A // Use the sentinel for a zero-length list
3057N/A suppressed = SUPPRESSED_SENTINEL;
3057N/A } else { // Copy Throwables to new list
3323N/A suppressed = new ArrayList<>(1);
3057N/A for (Throwable t : suppressedExceptions) {
3057N/A // Enforce constraints on suppressed exceptions in
3057N/A // case of corrupt or malicious stream.
3057N/A if (t == null)
3057N/A throw new NullPointerException(NULL_CAUSE_MESSAGE);
3057N/A if (t == this)
3057N/A throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
3057N/A suppressed.add(t);
3057N/A }
2548N/A }
3057N/A suppressedExceptions = suppressed;
3057N/A } // else a null suppressedExceptions field remains null
3057N/A
4116N/A /*
4116N/A * For zero-length stack traces, use a clone of
4116N/A * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
4116N/A * allow identity comparison against UNASSIGNED_STACK in
4116N/A * getOurStackTrace. The identity of UNASSIGNED_STACK in
4116N/A * stackTrace indicates to the getOurStackTrace method that
4116N/A * the stackTrace needs to be constructed from the information
4116N/A * in backtrace.
4116N/A */
3057N/A if (stackTrace != null) {
4116N/A if (stackTrace.length == 0) {
4116N/A stackTrace = UNASSIGNED_STACK.clone();
4116N/A } else if (stackTrace.length == 1 &&
4116N/A // Check for the marker of an immutable stack trace
4116N/A SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) {
4116N/A stackTrace = null;
4116N/A } else { // Verify stack trace elements are non-null.
4116N/A for(StackTraceElement ste : stackTrace) {
4116N/A if (ste == null)
4116N/A throw new NullPointerException("null StackTraceElement in serial stream. ");
4116N/A }
3057N/A }
3057N/A } else {
4116N/A // A null stackTrace field in the serial form can result
4116N/A // from an exception serialized without that field in
4116N/A // older JDK releases; treat such exceptions as having
4116N/A // empty stack traces.
4116N/A stackTrace = UNASSIGNED_STACK.clone();
2548N/A }
2548N/A }
2548N/A
3057N/A /**
3057N/A * Write a {@code Throwable} object to a stream.
4116N/A *
4116N/A * A {@code null} stack trace field is represented in the serial
4116N/A * form as a one-element array whose element is equal to {@code
4116N/A * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
3057N/A */
2548N/A private synchronized void writeObject(ObjectOutputStream s)
3057N/A throws IOException {
4116N/A // Ensure that the stackTrace field is initialized to a
4116N/A // non-null value, if appropriate. As of JDK 7, a null stack
4116N/A // trace field is a valid value indicating the stack trace
4116N/A // should not be set.
4116N/A getOurStackTrace();
4116N/A
4137N/A StackTraceElement[] oldStackTrace = stackTrace;
4137N/A try {
4137N/A if (stackTrace == null)
4137N/A stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
4137N/A s.defaultWriteObject();
4137N/A } finally {
4137N/A stackTrace = oldStackTrace;
4137N/A }
0N/A }
2548N/A
2548N/A /**
3399N/A * Appends the specified exception to the exceptions that were
3399N/A * suppressed in order to deliver this exception. This method is
4220N/A * thread-safe and typically called (automatically and implicitly)
4220N/A * by the {@code try}-with-resources statement.
2548N/A *
3894N/A * <p>The suppression behavior is enabled <em>unless</em> disabled
4116N/A * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
4116N/A * a constructor}. When suppression is disabled, this method does
3894N/A * nothing other than to validate its argument.
3057N/A *
2607N/A * <p>Note that when one exception {@linkplain
2607N/A * #initCause(Throwable) causes} another exception, the first
2607N/A * exception is usually caught and then the second exception is
3879N/A * thrown in response. In other words, there is a causal
3879N/A * connection between the two exceptions.
3879N/A *
3879N/A * In contrast, there are situations where two independent
3879N/A * exceptions can be thrown in sibling code blocks, in particular
3879N/A * in the {@code try} block of a {@code try}-with-resources
3879N/A * statement and the compiler-generated {@code finally} block
3879N/A * which closes the resource.
3879N/A *
3879N/A * In these situations, only one of the thrown exceptions can be
3879N/A * propagated. In the {@code try}-with-resources statement, when
3879N/A * there are two such exceptions, the exception originating from
3879N/A * the {@code try} block is propagated and the exception from the
3879N/A * {@code finally} block is added to the list of exceptions
3879N/A * suppressed by the exception from the {@code try} block. As an
3879N/A * exception unwinds the stack, it can accumulate multiple
3879N/A * suppressed exceptions.
3879N/A *
3879N/A * <p>An exception may have suppressed exceptions while also being
3879N/A * caused by another exception. Whether or not an exception has a
3879N/A * cause is semantically known at the time of its creation, unlike
3879N/A * whether or not an exception will suppress other exceptions
3879N/A * which is typically only determined after an exception is
3879N/A * thrown.
3879N/A *
3879N/A * <p>Note that programmer written code is also able to take
3879N/A * advantage of calling this method in situations where there are
3879N/A * multiple sibling exceptions and only one can be propagated.
2607N/A *
2548N/A * @param exception the exception to be added to the list of
2548N/A * suppressed exceptions
2607N/A * @throws IllegalArgumentException if {@code exception} is this
2607N/A * throwable; a throwable cannot suppress itself.
3894N/A * @throws NullPointerException if {@code exception} is {@code null}
2548N/A * @since 1.7
2548N/A */
3057N/A public final synchronized void addSuppressed(Throwable exception) {
2607N/A if (exception == this)
6141N/A throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception);
3057N/A
3894N/A if (exception == null)
3894N/A throw new NullPointerException(NULL_CAUSE_MESSAGE);
2548N/A
3894N/A if (suppressedExceptions == null) // Suppressed exceptions not recorded
3894N/A return;
3057N/A
3894N/A if (suppressedExceptions == SUPPRESSED_SENTINEL)
3894N/A suppressedExceptions = new ArrayList<>(1);
3057N/A
3894N/A suppressedExceptions.add(exception);
2548N/A }
2548N/A
2548N/A private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
2548N/A
2548N/A /**
2548N/A * Returns an array containing all of the exceptions that were
2726N/A * suppressed, typically by the {@code try}-with-resources
2548N/A * statement, in order to deliver this exception.
2548N/A *
3894N/A * If no exceptions were suppressed or {@linkplain
4116N/A * #Throwable(String, Throwable, boolean, boolean) suppression is
4220N/A * disabled}, an empty array is returned. This method is
4220N/A * thread-safe. Writes to the returned array do not affect future
4220N/A * calls to this method.
3057N/A *
2548N/A * @return an array containing all of the exceptions that were
2548N/A * suppressed to deliver this exception.
2548N/A * @since 1.7
2548N/A */
3057N/A public final synchronized Throwable[] getSuppressed() {
3057N/A if (suppressedExceptions == SUPPRESSED_SENTINEL ||
3057N/A suppressedExceptions == null)
2656N/A return EMPTY_THROWABLE_ARRAY;
2656N/A else
2656N/A return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
2548N/A }
0N/A}