Throwable.java revision 4137
2362N/A * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. 0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 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 * 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 * 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. 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 0N/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 0N/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 0N/A * {@code catch} clause. 0N/A * For the purposes of compile-time checking of exceptions, {@code 0N/A * Throwable} and any subclass of {@code Throwable} that is not also a 0N/A * subclass of either {@link RuntimeException} or {@link Error} are 0N/A * regarded as checked exceptions. 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 * <p>A throwable contains a snapshot of the execution stack of its 0N/A * thread at the time it was created. It can also contain a message 0N/A * string that gives more information about the error. Over time, a 0N/A * throwable can {@linkplain Throwable#addSuppressed suppress} other 0N/A * throwables from being propagated. Finally, the throwable can also 0N/A * contain a <i>cause</i>: another throwable that caused this 0N/A * throwable to be constructed. The recording of this causal information 0N/A * is referred to as the <i>chained exception</i> facility, as the 0N/A * cause can, itself, have a cause, and so on, leading to a "chain" of 0N/A * exceptions, each caused by another. 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 * <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 0N/A * {@code java.io}. Suppose the internals of the {@code add} method 0N/A * can throw an {@link java.io.IOException IOException}. The implementation 0N/A * can communicate the details of the {@code IOException} to its caller 0N/A * while conforming to the {@code Collection} interface by wrapping the 0N/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 * <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 0N/A * {@code Throwable} constructors that takes a cause. 0N/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 0N/A * {@code Throwable}. 0N/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 0N/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 0N/A * {@code Throwable} (the cause), and one that takes a 0N/A * {@code String} (the detail message) and a {@code Throwable} (the 0N/A * @author unascribed 0N/A * @author Josh Bloch (Added exception chaining and programmatic access to 0N/A * stack trace in 1.4.) 0N/A * @jls 11.2 Compile-Time Checking of Exceptions 0N/A /** use serialVersionUID from JDK 1.0.2 for interoperability */ 0N/A * Native code saves some indication of the stack backtrace in this slot. 0N/A * Specific details about the Throwable. For example, for 0N/A * {@code FileNotFoundException}, this contains the name of 0N/A * the file that could not be found. 0N/A * Holder class to defer initializing sentinel objects only used 0N/A * for serialization. 0N/A * {@linkplain #setStackTrace(StackTraceElement[]) Setting the 0N/A * stack trace} to a one-element array containing this sentinel 0N/A * value indicates future attempts to set the stack trace will be 0N/A * ignored. The sentinal is equal to the result of calling:<br> 0N/A * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)} 0N/A * Sentinel value used in the serial form to indicate an immutable 0N/A * A shared value for an empty stack. 0N/A * To allow Throwable objects to be made immutable and safely 0N/A * reused by the JVM, such as OutOfMemoryErrors, fields of 0N/A * Throwable that are writable in response to user actions, cause, 0N/A * stackTrace, and suppressedExceptions obey the following 0N/A * 1) The fields are initialized to a non-null sentinel value 0N/A * which indicates the value has logically not been set. 0N/A * 2) Writing a null to the field indicates further writes 0N/A * 3) The sentinel value may be replaced with another non-null 0N/A * For example, implementations of the HotSpot JVM have 0N/A * preallocated OutOfMemoryError objects to provide for better 0N/A * diagnosability of that situation. These objects are created 0N/A * without calling the constructor for that class and the fields 0N/A * in question are initialized to null. To support this 0N/A * capability, any new fields added to Throwable that require 0N/A * being initialized to a non-null value require a coordinated JVM 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 * The stack trace, as returned by {@link #getStackTrace()}. 0N/A * The field is initialized to a zero-length array. A {@code 0N/A * null} value of this field indicates subsequent calls to {@link 0N/A * #setStackTrace(StackTraceElement[])} and {@link 0N/A * #fillInStackTrace()} will be be no-ops. 0N/A // Setting this static field introduces an acceptable 0N/A // initialization dependency on a few java.util classes. 3813N/A * The list of suppressed exceptions, as returned by {@link 3813N/A * #getSuppressed()}. The list is initialized to a zero-element 3813N/A * unmodifiable sentinel list. When a serialized Throwable is 0N/A * read in, if the {@code suppressedExceptions} field points to a 0N/A * zero-element list, the field is reset to the sentinel value. 0N/A /** Message for trying to suppress a null exception. */ 3813N/A /** Message for trying to suppress oneself. */ 3813N/A /** Caption for labeling causative exception stack traces */ 0N/A /** Caption for labeling suppressed exception stack traces */ 0N/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 * <p>The {@link #fillInStackTrace()} method is called to initialize 0N/A * the stack trace data in the newly created throwable. 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 * <p>The {@link #fillInStackTrace()} method is called to initialize 0N/A * the stack trace data in the newly created throwable. 0N/A * @param message the detail message. The detail message is saved for 0N/A * later retrieval by the {@link #getMessage()} method. 0N/A * Constructs a new throwable with the specified detail message and 0N/A * cause. <p>Note that the detail message associated with 0N/A * {@code cause} is <i>not</i> automatically incorporated in 0N/A * this throwable's detail message. 0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize 0N/A * the stack trace data in the newly created throwable. 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 0N/A * {@link #getCause()} method). (A {@code null} value is 0N/A * permitted, and indicates that the cause is nonexistent or 0N/A * Constructs a new throwable with the specified cause and a detail 3813N/A * message of {@code (cause==null ? null : cause.toString())} (which 3813N/A * typically contains the class and detail message of {@code cause}). 3813N/A * This constructor is useful for throwables that are little more than 3813N/A * wrappers for other throwables (for example, {@link 3813N/A * java.security.PrivilegedActionException}). 0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize 0N/A * the stack trace data in the newly created throwable. 0N/A * @param cause the cause (which is saved for later retrieval by the 0N/A * {@link #getCause()} method). (A {@code null} value is 0N/A * permitted, and indicates that the cause is nonexistent or * Constructs a new throwable with the specified detail message, * cause, {@linkplain #addSuppressed suppression} enabled or * disabled, and writable stack trace enabled or disabled. If * suppression is disabled, {@link #getSuppressed} for this object * will return a zero-length array and calls to {@link * #addSuppressed} that would otherwise append an exception to the * suppressed list will have no effect. If the writable stack * trace is false, this constructor will not call {@link * #fillInStackTrace()}, a {@code null} will be written to the * {@code stackTrace} field, and subsequent calls to {@code * fillInStackTrace} and {@link * #setStackTrace(StackTraceElement[])} will not set the stack * trace. If the writable stack trace is false, {@link * #getStackTrace} will return a zero length array. * <p>Note that the other constructors of {@code Throwable} treat * suppression as being enabled and the stack trace as being * writable. Subclasses of {@code Throwable} should document any * conditions under which suppression is disabled and document * conditions under which the stack trace is not writable. * Disabling of suppression should only occur in exceptional * circumstances where special requirements exist, such as a * virtual machine reusing exception objects under low-memory * @param message the detail message. * @param cause the cause. (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @param enableSuppression whether or not suppression is enabled or disabled * @param writableStackTrace whether or not the stack trace should be * @see NullPointerException * @see ArithmeticException * Returns the detail message string of this throwable. * @return the detail message string of this {@code Throwable} instance * (which may be {@code null}). * Creates a localized description of this throwable. * Subclasses may override this method in order to produce a * locale-specific message. For subclasses that do not override this * method, the default implementation returns the same result as * @return The localized description of this throwable. * Returns the cause of this throwable or {@code null} if the * cause is nonexistent or unknown. (The cause is the throwable that * caused this throwable to get thrown.) * <p>This implementation returns the cause that was supplied via one of * the constructors requiring a {@code Throwable}, or that was set after * creation with the {@link #initCause(Throwable)} method. While it is * typically unnecessary to override this method, a subclass can override * it to return a cause set by some other means. This is appropriate for * a "legacy chained throwable" that predates the addition of chained * exceptions to {@code Throwable}. Note that it is <i>not</i> * necessary to override any of the {@code PrintStackTrace} methods, * all of which invoke the {@code getCause} method to determine the * @return the cause of this throwable or {@code null} if the * cause is nonexistent or unknown. * Initializes the <i>cause</i> of this throwable to the specified value. * (The cause is the throwable that caused this throwable to get thrown.) * <p>This method can be called at most once. It is generally called from * within the constructor, or immediately after creating the * throwable. If this throwable was created * with {@link #Throwable(Throwable)} or * {@link #Throwable(String,Throwable)}, this method cannot be called * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * @return a reference to this {@code Throwable} instance. * @throws IllegalArgumentException if {@code cause} is this * throwable. (A throwable cannot be its own cause.) * @throws IllegalStateException if this throwable was * created with {@link #Throwable(Throwable)} or * {@link #Throwable(String,Throwable)}, or this method has already * been called on this throwable. * Returns a short description of this throwable. * The result is the concatenation of: * <li> the {@linkplain Class#getName() name} of the class of this object * <li> ": " (a colon and a space) * <li> the result of invoking this object's {@link #getLocalizedMessage} * If {@code getLocalizedMessage} returns {@code null}, then just * the class name is returned. * @return a string representation of this throwable. * Prints this throwable and its backtrace to the * standard error stream. This method prints a stack trace for this * {@code Throwable} object on the error output stream that is * the value of the field {@code System.err}. The first line of * output contains the result of the {@link #toString()} method for * this object. Remaining lines represent data previously recorded by * the method {@link #fillInStackTrace()}. The format of this * information depends on the implementation, but the following * example may be regarded as typical: * java.lang.NullPointerException * This example was produced by running the program: * public static void main(String[] args) { * static void crunch(int[] a) { * static void mash(int[] b) { * System.out.println(b[0]); * The backtrace for a throwable with an initialized, non-null cause * should generally include the backtrace for the cause. The format * of this information depends on the implementation, but the following * example may be regarded as typical: * HighLevelException: MidLevelException: LowLevelException * Caused by: MidLevelException: LowLevelException * Caused by: LowLevelException * Note the presence of lines containing the characters {@code "..."}. * These lines indicate that the remainder of the stack trace for this * exception matches the indicated number of frames from the bottom of the * stack trace of the exception that was caused by this exception (the * "enclosing" exception). This shorthand can greatly reduce the length * of the output in the common case where a wrapped exception is thrown * from same method as the "causative exception" is caught. The above * example was produced by running the program: * public static void main(String args[]) { * } catch(HighLevelException e) { * static void a() throws HighLevelException { * } catch(MidLevelException e) { * throw new HighLevelException(e); * static void b() throws MidLevelException { * static void c() throws MidLevelException { * } catch(LowLevelException e) { * throw new MidLevelException(e); * static void d() throws LowLevelException { * static void e() throws LowLevelException { * throw new LowLevelException(); * class HighLevelException extends Exception { * HighLevelException(Throwable cause) { super(cause); } * class MidLevelException extends Exception { * MidLevelException(Throwable cause) { super(cause); } * class LowLevelException extends Exception { * As of release 7, the platform supports the notion of * <i>suppressed exceptions</i> (in conjunction with the {@code * try}-with-resources statement). Any exceptions that were * suppressed in order to deliver an exception are printed out * beneath the stack trace. The format of this information * depends on the implementation, but the following example may be * Exception in thread "main" java.lang.Exception: Something happened * Suppressed: Resource$CloseFailException: Resource ID = 0 * Note that the "... n more" notation is used on suppressed exceptions * just at it is used on causes. Unlike causes, suppressed exceptions are * indented beyond their "containing exceptions." * <p>An exception can have both a cause and one or more suppressed * Exception in thread "main" java.lang.Exception: Main block * Suppressed: Resource$CloseFailException: Resource ID = 2 * Suppressed: Resource$CloseFailException: Resource ID = 1 * Caused by: java.lang.Exception: I did it * Likewise, a suppressed exception can have a cause: * Exception in thread "main" java.lang.Exception: Main block * Suppressed: Resource2$CloseFailException: Resource ID = 1 * Caused by: java.lang.Exception: Rats, you caught me * Prints this throwable and its backtrace to the specified print stream. * @param s {@code PrintStream} to use for output // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.
lock()) {
// Print suppressed exceptions, if any * Print our stack trace as an enclosed exception for the specified s.
println(
"\t[CIRCULAR REFERENCE:" +
this +
"]");
// Compute number of frames in common between this and enclosing trace for (
int i =
0; i <= m; i++)
// Print suppressed exceptions, if any * Prints this throwable and its backtrace to the specified * @param s {@code PrintWriter} to use for output * Wrapper class for PrintStream and PrintWriter to enable a single * implementation of printStackTrace. /** Returns the object to be locked when using this StreamOrWriter */ /** Prints the specified string as a line on this StreamOrWriter */ * Fills in the execution stack trace. This method records within this * {@code Throwable} object information about the current state of * the stack frames for the current thread. * <p>If the stack trace of this {@code Throwable} {@linkplain * Throwable#Throwable(String, Throwable, boolean, boolean) is not * writable}, calling this method has no effect. * @return a reference to this {@code Throwable} instance. * @see java.lang.Throwable#printStackTrace() * Provides programmatic access to the stack trace information printed by * {@link #printStackTrace()}. Returns an array of stack trace elements, * each representing one stack frame. The zeroth element of the array * (assuming the array's length is non-zero) represents the top of the * stack, which is the last method invocation in the sequence. Typically, * this is the point at which this throwable was created and thrown. * The last element of the array (assuming the array's length is non-zero) * represents the bottom of the stack, which is the first method invocation * <p>Some virtual machines may, under some circumstances, omit one * or more stack frames from the stack trace. In the extreme case, * a virtual machine that has no stack trace information concerning * this throwable is permitted to return a zero-length array from this * method. Generally speaking, the array returned by this method will * contain one element for every frame that would be printed by * {@code printStackTrace}. * @return an array of stack trace elements representing the stack trace * pertaining to this throwable. // Initialize stack trace field with information from // backtrace if this is the first call to this method for (
int i=
0; i <
depth; i++)
* Sets the stack trace elements that will be returned by * {@link #getStackTrace()} and printed by {@link #printStackTrace()} * This method, which is designed for use by RPC frameworks and other * advanced systems, allows the client to override the default * stack trace that is either generated by {@link #fillInStackTrace()} * when a throwable is constructed or deserialized when a throwable is * read from a serialization stream. * <p>If the stack trace of this {@code Throwable} {@linkplain * Throwable#Throwable(String, Throwable, boolean, boolean) is not * writable}, calling this method has no effect other than * validating its argument. * @param stackTrace the stack trace elements to be associated with * this {@code Throwable}. The specified array is copied by this * call; changes in the specified array after the method invocation * returns will have no affect on this {@code Throwable}'s stack * @throws NullPointerException if {@code stackTrace} is * {@code null} or if any of the elements of * {@code stackTrace} are {@code null} * Returns the number of elements in the stack trace (or 0 if the stack * package-protection for use by SharedSecrets. * Returns the specified element of the stack trace. * package-protection for use by SharedSecrets. * @param index index of the element to return. * @throws IndexOutOfBoundsException if {@code index < 0 || * index >= getStackTraceDepth() } * Reads a {@code Throwable} from a stream, enforcing * well-formedness constraints on fields. Null entries and * self-pointers are not allowed in the list of {@code * suppressedExceptions}. Null entries are not allowed for stack * trace elements. A null stack trace in the serial form results * in a zero-length stack element array. A single-element stack * trace whose entry is equal to {@code new StackTraceElement("", * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code * Note that there are no constraints on the value the {@code * cause} field can hold; both {@code null} and {@code this} are * valid values for the field. // Use the sentinel for a zero-length list }
else {
// Copy Throwables to new list // Enforce constraints on suppressed exceptions in // case of corrupt or malicious stream. }
// else a null suppressedExceptions field remains null * For zero-length stack traces, use a clone of * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to * allow identity comparison against UNASSIGNED_STACK in * getOurStackTrace. The identity of UNASSIGNED_STACK in * stackTrace indicates to the getOurStackTrace method that * the stackTrace needs to be constructed from the information // Check for the marker of an immutable stack trace }
else {
// Verify stack trace elements are non-null. // A null stackTrace field in the serial form can result // from an exception serialized without that field in // older JDK releases; treat such exceptions as having * Write a {@code Throwable} object to a stream. * A {@code null} stack trace field is represented in the serial * form as a one-element array whose element is equal to {@code * new StackTraceElement("", "", null, Integer.MIN_VALUE)}. // Ensure that the stackTrace field is initialized to a // non-null value, if appropriate. As of JDK 7, a null stack // trace field is a valid value indicating the stack trace * Appends the specified exception to the exceptions that were * suppressed in order to deliver this exception. This method is * typically called (automatically and implicitly) by the {@code * try}-with-resources statement. * <p>The suppression behavior is enabled <em>unless</em> disabled * {@linkplain #Throwable(String, Throwable, boolean, boolean) via * a constructor}. When suppression is disabled, this method does * nothing other than to validate its argument. * <p>Note that when one exception {@linkplain * #initCause(Throwable) causes} another exception, the first * exception is usually caught and then the second exception is * thrown in response. In other words, there is a causal * connection between the two exceptions. * In contrast, there are situations where two independent * exceptions can be thrown in sibling code blocks, in particular * in the {@code try} block of a {@code try}-with-resources * statement and the compiler-generated {@code finally} block * which closes the resource. * In these situations, only one of the thrown exceptions can be * propagated. In the {@code try}-with-resources statement, when * there are two such exceptions, the exception originating from * the {@code try} block is propagated and the exception from the * {@code finally} block is added to the list of exceptions * suppressed by the exception from the {@code try} block. As an * exception unwinds the stack, it can accumulate multiple * <p>An exception may have suppressed exceptions while also being * caused by another exception. Whether or not an exception has a * cause is semantically known at the time of its creation, unlike * whether or not an exception will suppress other exceptions * which is typically only determined after an exception is * <p>Note that programmer written code is also able to take * advantage of calling this method in situations where there are * multiple sibling exceptions and only one can be propagated. * @param exception the exception to be added to the list of * @throws IllegalArgumentException if {@code exception} is this * throwable; a throwable cannot suppress itself. * @throws NullPointerException if {@code exception} is {@code null} * Returns an array containing all of the exceptions that were * suppressed, typically by the {@code try}-with-resources * statement, in order to deliver this exception. * If no exceptions were suppressed or {@linkplain * #Throwable(String, Throwable, boolean, boolean) suppression is * disabled}, an empty array is returned. * @return an array containing all of the exceptions that were * suppressed to deliver this exception.