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