Top Description Inners Fields Constructors Methods
java.lang

public Class Throwable

extends Object
implements Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable
Known Direct Subclasses
java.lang.Error, java.lang.Exception
Imports
java.io.*, java.util.*, jdk.internal.access.SharedSecrets, jdk.internal.event.ThrowableTracer, jdk.internal.misc.InternalLock

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause. For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.

Instances of two subclasses, java.lang.Error and java.lang.Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).

A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Over time, a throwable can suppress other throwables from being propagated. Finally, the throwable can also contain a cause: another throwable that caused this throwable to be constructed. The recording of this causal information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another.

One reason that a throwable may have a cause is that the class that throws it is built atop a lower layered abstraction, and an operation on the upper layer fails due to a failure in the lower layer. It would be bad design to let the throwable thrown by the lower layer propagate outward, as it is generally unrelated to the abstraction provided by the upper layer. Further, doing so would tie the API of the upper layer to the details of its implementation, assuming the lower layer's exception was a checked exception. Throwing a "wrapped exception" (i.e., an exception containing a cause) allows the upper layer to communicate the details of the failure to its caller without incurring either of these shortcomings. It preserves the flexibility to change the implementation of the upper layer without changing its API (in particular, the set of exceptions thrown by its methods).

A second reason that a throwable may have a cause is that the method that throws it must conform to a general-purpose interface that does not permit the method to throw the cause directly. For example, suppose a persistent collection conforms to the Collection interface, and that its persistence is implemented atop java.io. Suppose the internals of the add method can throw an IOException. The implementation can communicate the details of the IOException to its caller while conforming to the Collection interface by wrapping the IOException in an appropriate unchecked exception. (The specification for the persistent collection should indicate that it is capable of throwing such exceptions.)

A cause can be associated with a throwable in two ways: via a constructor that takes the cause as an argument, or via the initCause(Throwable) method. New throwable classes that wish to allow causes to be associated with them should provide constructors that take a cause and delegate (perhaps indirectly) to one of the Throwable constructors that takes a cause. Because the initCause method is public, it allows a cause to be associated with any throwable, even a "legacy throwable" whose implementation predates the addition of the exception chaining mechanism to Throwable.

By convention, class Throwable and its subclasses have two constructors, one that takes no arguments and one that takes a String argument that can be used to produce a detail message. Further, those subclasses that might likely have a cause associated with them should have two more constructors, one that takes a Throwable (the cause), and one that takes a String (the detail message) and a Throwable (the cause).

Author
Josh Bloch (Added exception chaining and programmatic access to stack trace in 1.4.)
Since
1.0
Java Language Specification
11.2 Compile-Time Checking of Exceptions

Nested and Inner Type Summary

Modifier and TypeClass and Description
private abstract static class
Throwable.PrintStreamOrWriter

Wrapper class for PrintStream and PrintWriter to enable a single implementation of printStackTrace.

private static class
Throwable.SentinelHolder

Holder class to defer initializing sentinel objects only used for serialization.

private static class
private static class

Field Summary

Modifier and TypeField and Description
private transient Object
backtrace

The JVM saves some indication of the stack backtrace in this slot.

private Throwable
cause

The throwable that caused this throwable to get thrown, or null if this throwable was not caused by another throwable, or if the causative throwable is unknown.

private static final String
CAUSE_CAPTION

Caption for labeling causative exception stack traces

private transient int
depth

The JVM code sets the depth of the backtrace for later retrieval

private String
detailMessage

Specific details about the Throwable.

private static final Throwable[]
pack-priv static volatile boolean
jfrTracing

Flag set by jdk.internal.event.JFRTracing to indicate if exceptions should be traced by JFR.

private static final String
NULL_CAUSE_MESSAGE

Message for trying to suppress a null exception.

private static final String
SELF_SUPPRESSION_MESSAGE

Message for trying to suppress oneself.

private static final long
serialVersionUID

use serialVersionUID from JDK 1.0.2 for interoperability

private StackTraceElement[]
stackTrace

The stack trace, as returned by getStackTrace().

private static final String
SUPPRESSED_CAPTION

Caption for labeling suppressed exception stack traces

private static final List<Throwable>
private List<Throwable>
suppressedExceptions

The list of suppressed exceptions, as returned by getSuppressed().

private static final StackTraceElement[]
UNASSIGNED_STACK

A shared value for an empty stack.

Constructor Summary

AccessConstructor and Description
public
Throwable()

Constructs a new throwable with null as its detail message.

public
Throwable(String
the detail message. The detail message is saved for later retrieval by the getMessage() method.
message
)

Constructs a new throwable with the specified detail message.

public
Throwable(String
the detail message (which is saved for later retrieval by the getMessage() method).
message
,
Throwable
the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
cause
)

Constructs a new throwable with the specified detail message and cause.

public
Throwable(Throwable
the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
cause
)

Constructs a new throwable with the specified cause and a detail message of (cause==null ?

protected
Throwable(String
the detail message.
message
,
Throwable
the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
cause
,
boolean
whether or not suppression is enabled
enableSuppression
,
boolean
whether or not the stack trace is writable
writableStackTrace
)

Constructs a new throwable with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Method Summary

Modifier and TypeMethod and Description
public final synchronized void
addSuppressed(Throwable
the exception to be added to the list of suppressed exceptions
exception
)

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

public synchronized Throwable

Returns:

a reference to this Throwable instance.
fillInStackTrace
()

Fills in the execution stack trace.

private native Throwable
fillInStackTrace(int dummy)

public synchronized Throwable

Returns:

the cause of this throwable or null if the cause is nonexistent or unknown.
getCause
()

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

public String

Returns:

The localized description of this throwable.
getLocalizedMessage
()

Creates a localized description of this throwable.

public String

Returns:

the detail message string of this Throwable instance (which may be null).
getMessage
()

Returns the detail message string of this throwable.

private synchronized StackTraceElement[]
public StackTraceElement[]

Returns:

an array of stack trace elements representing the stack trace pertaining to this throwable.
getStackTrace
()

Provides programmatic access to the stack trace information printed by printStackTrace().

public final synchronized Throwable[]

Returns:

an array containing all of the exceptions that were suppressed to deliver this exception.
getSuppressed
()

Returns an array containing all of the exceptions that were suppressed, typically by the try-with-resources statement, in order to deliver this exception.

public synchronized Throwable

Returns:

a reference to this Throwable instance.
initCause
(Throwable
the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
cause
)

Initializes the cause of this throwable to the specified value.

private void
private void
printEnclosedStackTrace(Throwable.PrintStreamOrWriter s, StackTraceElement[] enclosingTrace, String caption, String prefix, Set<Throwable> dejaVu)

Print our stack trace as an enclosed exception for the specified stack trace.

public void
printStackTrace()

Prints this throwable and its backtrace to the standard error stream.

public void
printStackTrace(PrintStream
PrintStream to use for output
s
)

Prints this throwable and its backtrace to the specified print stream.

private void
public void
printStackTrace(PrintWriter
PrintWriter to use for output
s
)

Prints this throwable and its backtrace to the specified print writer.

private void
readObject(ObjectInputStream
the ObjectInputStream from which data is read
s
)

Reads a Throwable from a stream, enforcing well-formedness constraints on fields.

pack-priv final void
public void
setStackTrace(StackTraceElement[]
the stack trace elements to be associated with this Throwable. The specified array is copied by this call; changes in the specified array after the method invocation returns will have no effect on this Throwable's stack trace.
stackTrace
)

Sets the stack trace elements that will be returned by getStackTrace() and printed by printStackTrace() and related methods.

public String

Returns:

a string representation of this throwable.
toString
()

Overrides java.lang.Object.toString.

Returns a short description of this throwable.

private int
validateSuppressedExceptionsList(List<Throwable> deserSuppressedExceptions)

private synchronized void
writeObject(ObjectOutputStream
the ObjectOutputStream to which data is written
s
)

Write a Throwable object to a stream.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

backtraceback to summary
private transient Object backtrace

The JVM saves some indication of the stack backtrace in this slot.

causeback to summary
private Throwable cause

The throwable that caused this throwable to get thrown, or null if this throwable was not caused by another throwable, or if the causative throwable is unknown. If this field is equal to this throwable itself, it indicates that the cause of this throwable has not yet been initialized.

Since
1.4
CAUSE_CAPTIONback to summary
private static final String CAUSE_CAPTION

Caption for labeling causative exception stack traces

depthback to summary
private transient int depth

The JVM code sets the depth of the backtrace for later retrieval

detailMessageback to summary
private String detailMessage

Specific details about the Throwable. For example, for FileNotFoundException, this contains the name of the file that could not be found.

EMPTY_THROWABLE_ARRAYback to summary
private static final Throwable[] EMPTY_THROWABLE_ARRAY
jfrTracingback to summary
pack-priv static volatile boolean jfrTracing

Flag set by jdk.internal.event.JFRTracing to indicate if exceptions should be traced by JFR.

NULL_CAUSE_MESSAGEback to summary
private static final String NULL_CAUSE_MESSAGE

Message for trying to suppress a null exception.

SELF_SUPPRESSION_MESSAGEback to summary
private static final String SELF_SUPPRESSION_MESSAGE

Message for trying to suppress oneself.

serialVersionUIDback to summary
private static final long serialVersionUID

use serialVersionUID from JDK 1.0.2 for interoperability

Annotations
@Serial
stackTraceback to summary
private StackTraceElement[] stackTrace

The stack trace, as returned by getStackTrace(). The field is initialized to a zero-length array. A null value of this field indicates subsequent calls to setStackTrace(StackTraceElement[]) and fillInStackTrace() will be no-ops.

Since
1.4
SUPPRESSED_CAPTIONback to summary
private static final String SUPPRESSED_CAPTION

Caption for labeling suppressed exception stack traces

SUPPRESSED_SENTINELback to summary
private static final List<Throwable> SUPPRESSED_SENTINEL
suppressedExceptionsback to summary
private List<Throwable> suppressedExceptions

The list of suppressed exceptions, as returned by getSuppressed(). The list is initialized to a zero-element unmodifiable sentinel list. When a serialized Throwable is read in, if the suppressedExceptions field points to a zero-element list, the field is reset to the sentinel value.

Annotations
@SuppressWarnings:serial
Since
1.7
UNASSIGNED_STACKback to summary
private static final StackTraceElement[] UNASSIGNED_STACK

A shared value for an empty stack.

Constructor Detail

Throwableback to summary
public Throwable()

Constructs a new throwable with null as its detail message. The cause is not initialized, and may subsequently be initialized by a call to initCause.

The fillInStackTrace() method is called to initialize the stack trace data in the newly created throwable.

Annotations
@SuppressWarnings:this-escape
Throwableback to summary
public Throwable(String message)

Constructs a new throwable with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to initCause.

The fillInStackTrace() method is called to initialize the stack trace data in the newly created throwable.

Parameters
message:String

the detail message. The detail message is saved for later retrieval by the getMessage() method.

Annotations
@SuppressWarnings:this-escape
Throwableback to summary
public Throwable(String message, Throwable cause)

Constructs a new throwable with the specified detail message and cause.

Note that the detail message associated with cause is not automatically incorporated in this throwable's detail message.

The fillInStackTrace() method is called to initialize the stack trace data in the newly created throwable.

Parameters
message:String

the detail message (which is saved for later retrieval by the getMessage() method).

cause:Throwable

the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)

Annotations
@SuppressWarnings:this-escape
Since
1.4
Throwableback to summary
public Throwable(Throwable cause)

Constructs a new throwable with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause). This constructor is useful for throwables that are little more than wrappers for other throwables (for example, java.security.PrivilegedActionException).

The fillInStackTrace() method is called to initialize the stack trace data in the newly created throwable.

Parameters
cause:Throwable

the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)

Annotations
@SuppressWarnings:this-escape
Since
1.4
Throwableback to summary
protected Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)

Constructs a new throwable with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled. If suppression is disabled, getSuppressed for this object will return a zero-length array and calls to 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 fillInStackTrace(), a null will be written to the stackTrace field, and subsequent calls to fillInStackTrace and setStackTrace(StackTraceElement[]) will not set the stack trace. If the writable stack trace is false, getStackTrace will return a zero length array.

Note that the other constructors of Throwable treat suppression as being enabled and the stack trace as being writable. Subclasses of 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 situations. Circumstances where a given exception object is repeatedly caught and rethrown, such as to implement control flow between two sub-systems, is another situation where immutable throwable objects would be appropriate.

Parameters
message:String

the detail message.

cause:Throwable

the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.)

enableSuppression:boolean

whether or not suppression is enabled

writableStackTrace:boolean

whether or not the stack trace is writable

Annotations
@SuppressWarnings:this-escape
Since
1.7
See Also
OutOfMemoryError, NullPointerException, ArithmeticException

Method Detail

addSuppressedback to summary
public final synchronized void addSuppressed(Throwable exception)

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception. This method is thread-safe and typically called (automatically and implicitly) by the try-with-resources statement.

The suppression behavior is enabled unless disabled via a constructor. When suppression is disabled, this method does nothing other than to validate its argument.

Note that when one exception 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 try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.

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 thrown.

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.

Parameters
exception:Throwable

the exception to be added to the list of suppressed exceptions

Exceptions
IllegalArgumentException:
if exception is this throwable; a throwable cannot suppress itself.
NullPointerException:
if exception is null
Since
1.7
fillInStackTraceback to summary
public synchronized Throwable fillInStackTrace()

Fills in the execution stack trace. This method records within this Throwable object information about the current state of the stack frames for the current thread.

If the stack trace of this Throwable is not writable, calling this method has no effect.

Returns:Throwable

a reference to this Throwable instance.

See Also
java.lang.Throwable#printStackTrace()
fillInStackTraceback to summary
private native Throwable fillInStackTrace(int dummy)
getCauseback to summary
public synchronized Throwable getCause()

Returns the cause of this throwable or null if the cause is nonexistent or unknown. (The cause is the throwable that caused this throwable to get thrown.)

This implementation returns the cause that was supplied via one of the constructors requiring a Throwable, or that was set after creation with the 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 Throwable. Note that it is not necessary to override any of the PrintStackTrace methods, all of which invoke the getCause method to determine the cause of a throwable.

Returns:Throwable

the cause of this throwable or null if the cause is nonexistent or unknown.

Since
1.4
getLocalizedMessageback to summary
public String getLocalizedMessage()

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 getMessage().

Returns:String

The localized description of this throwable.

Since
1.1
getMessageback to summary
public String getMessage()

Returns the detail message string of this throwable.

Returns:String

the detail message string of this Throwable instance (which may be null).

getOurStackTraceback to summary
private synchronized StackTraceElement[] getOurStackTrace()
getStackTraceback to summary
public StackTraceElement[] getStackTrace()

Provides programmatic access to the stack trace information printed by 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 in the sequence.

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 printStackTrace. Writes to the returned array do not affect future calls to this method.

Returns:StackTraceElement[]

an array of stack trace elements representing the stack trace pertaining to this throwable.

Since
1.4
getSuppressedback to summary
public final synchronized Throwable[] getSuppressed()

Returns an array containing all of the exceptions that were suppressed, typically by the try-with-resources statement, in order to deliver this exception. If no exceptions were suppressed or suppression is disabled, an empty array is returned. This method is thread-safe. Writes to the returned array do not affect future calls to this method.

Returns:Throwable[]

an array containing all of the exceptions that were suppressed to deliver this exception.

Since
1.7
initCauseback to summary
public synchronized Throwable initCause(Throwable cause)

Initializes the cause of this throwable to the specified value. (The cause is the throwable that caused this throwable to get thrown.)

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 Throwable(Throwable) or Throwable(String, Throwable), this method cannot be called even once.

An example of using this method on a legacy throwable type without other support for setting the cause is:

try {
    lowLevelOp();
} catch (LowLevelException le) {
    throw (HighLevelException)
          new HighLevelException().initCause(le); // Legacy constructor
}
Parameters
cause:Throwable

the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)

Returns:Throwable

a reference to this Throwable instance.

Exceptions
IllegalArgumentException:
if cause is this throwable. (A throwable cannot be its own cause.)
IllegalStateException:
if this throwable was created with Throwable(Throwable) or Throwable(String, Throwable), or this method has already been called on this throwable.
Since
1.4
lockedPrintStackTraceback to summary
private void lockedPrintStackTrace(Throwable.PrintStreamOrWriter s)
printEnclosedStackTraceback to summary
private void printEnclosedStackTrace(Throwable.PrintStreamOrWriter s, StackTraceElement[] enclosingTrace, String caption, String prefix, Set<Throwable> dejaVu)

Print our stack trace as an enclosed exception for the specified stack trace.

printStackTraceback to summary
public void printStackTrace()

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends on the implementation, but the following example may be regarded as typical:

java.lang.NullPointerException
        at MyClass.mash(MyClass.java:9)
        at MyClass.crunch(MyClass.java:6)
        at MyClass.main(MyClass.java:3)
This example was produced by running the program:
class MyClass {
    public static void main(String[] args) {
        crunch(null);
    }
    static void crunch(int[] a) {
        mash(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
        at Junk.a(Junk.java:13)
        at Junk.main(Junk.java:4)
Caused by: MidLevelException: LowLevelException
        at Junk.c(Junk.java:23)
        at Junk.b(Junk.java:17)
        at Junk.a(Junk.java:11)
        ... 1 more
Caused by: LowLevelException
        at Junk.e(Junk.java:30)
        at Junk.d(Junk.java:27)
        at Junk.c(Junk.java:21)
        ... 3 more
Note the presence of lines containing the characters "...". 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 the same method as the "causative exception" is caught. The above example was produced by running the program:
public class Junk {
    public static void main(String args[]) {
        try {
            a();
        } catch(HighLevelException e) {
            e.printStackTrace();
        }
    }
    static void a() throws HighLevelException {
        try {
            b();
        } catch(MidLevelException e) {
            throw new HighLevelException(e);
        }
    }
    static void b() throws MidLevelException {
        c();
    }
    static void c() throws MidLevelException {
        try {
            d();
        } catch(LowLevelException e) {
            throw new MidLevelException(e);
        }
    }
    static void d() throws LowLevelException {
       e();
    }
    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 suppressed exceptions (in conjunction with the 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 regarded as typical:
Exception in thread "main" java.lang.Exception: Something happened
        at Foo.bar(Foo.java:10)
        at Foo.main(Foo.java:5)
        Suppressed: Resource$CloseFailException: Resource ID = 0
                at Resource.close(Resource.java:26)
                at Foo.bar(Foo.java:9)
                ... 1 more
Note that the "... n more" notation is used on suppressed exceptions just as it is used on causes. Unlike causes, suppressed exceptions are indented beyond their "containing exceptions."

An exception can have both a cause and one or more suppressed exceptions:

Exception in thread "main" java.lang.Exception: Main block
        at Foo3.main(Foo3.java:7)
        Suppressed: Resource$CloseFailException: Resource ID = 2
                at Resource.close(Resource.java:26)
                at Foo3.main(Foo3.java:5)
        Suppressed: Resource$CloseFailException: Resource ID = 1
                at Resource.close(Resource.java:26)
                at Foo3.main(Foo3.java:5)
Caused by: java.lang.Exception: I did it
        at Foo3.main(Foo3.java:8)
Likewise, a suppressed exception can have a cause:
Exception in thread "main" java.lang.Exception: Main block
        at Foo4.main(Foo4.java:6)
        Suppressed: Resource2$CloseFailException: Resource ID = 1
                at Resource2.close(Resource2.java:20)
                at Foo4.main(Foo4.java:5)
        Caused by: java.lang.Exception: Rats, you caught me
                at Resource2$CloseFailException.<init>(Resource2.java:45)
                ... 2 more
printStackTraceback to summary
public void printStackTrace(PrintStream s)

Prints this throwable and its backtrace to the specified print stream.

Parameters
s:PrintStream

PrintStream to use for output

printStackTraceback to summary
private void printStackTrace(Throwable.PrintStreamOrWriter s)
printStackTraceback to summary
public void printStackTrace(PrintWriter s)

Prints this throwable and its backtrace to the specified print writer.

Parameters
s:PrintWriter

PrintWriter to use for output

Since
1.1
readObjectback to summary
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException

Reads a Throwable from a stream, enforcing well-formedness constraints on fields. Null entries and self-pointers are not allowed in the list of 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 new StackTraceElement("", "", null, Integer.MIN_VALUE) results in a null stackTrace field. Note that there are no constraints on the value the cause field can hold; both null and this are valid values for the field.

Parameters
s:ObjectInputStream

the ObjectInputStream from which data is read

Annotations
@Serial
Exceptions
IOException:
if an I/O error occurs
ClassNotFoundException:
if a serialized class cannot be loaded
setCauseback to summary
pack-priv final void setCause(Throwable t)
setStackTraceback to summary
public void setStackTrace(StackTraceElement[] stackTrace)

Sets the stack trace elements that will be returned by getStackTrace() and printed by printStackTrace() and related methods. 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 fillInStackTrace() when a throwable is constructed or deserialized when a throwable is read from a serialization stream.

If the stack trace of this Throwable is not writable, calling this method has no effect other than validating its argument.

Parameters
stackTrace:StackTraceElement[]

the stack trace elements to be associated with this Throwable. The specified array is copied by this call; changes in the specified array after the method invocation returns will have no effect on this Throwable's stack trace.

Exceptions
NullPointerException:
if stackTrace is null or if any of the elements of stackTrace are null
Since
1.4
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Returns a short description of this throwable. The result is the concatenation of:

  • the name of the class of this object
  • ": " (a colon and a space)
  • the result of invoking this object's getLocalizedMessage method
If getLocalizedMessage returns null, then just the class name is returned.
Returns:String

a string representation of this throwable.

validateSuppressedExceptionsListback to summary
private int validateSuppressedExceptionsList(List<Throwable> deserSuppressedExceptions) throws IOException
writeObjectback to summary
private synchronized void writeObject(ObjectOutputStream s) throws IOException

Write a Throwable object to a stream. A null stack trace field is represented in the serial form as a one-element array whose element is equal to new StackTraceElement("", "", null, Integer.MIN_VALUE).

Parameters
s:ObjectOutputStream

the ObjectOutputStream to which data is written

Annotations
@Serial
Exceptions
IOException:
if an I/O error occurs
java.lang back to summary

private abstract Class Throwable.PrintStreamOrWriter

extends Object
Class Inheritance
Known Direct Subclasses
java.lang.Throwable.WrappedPrintStream, java.lang.Throwable.WrappedPrintWriter

Wrapper class for PrintStream and PrintWriter to enable a single implementation of printStackTrace.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
pack-priv boolean
pack-priv abstract Object
lock()

Returns the object to be locked when using this StreamOrWriter

pack-priv abstract void
println(Object o)

Prints the specified string as a line on this StreamOrWriter

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

PrintStreamOrWriterback to summary
private PrintStreamOrWriter()

Method Detail

isLockedByCurrentThreadback to summary
pack-priv boolean isLockedByCurrentThread()
lockback to summary
pack-priv abstract Object lock()

Returns the object to be locked when using this StreamOrWriter

printlnback to summary
pack-priv abstract void println(Object o)

Prints the specified string as a line on this StreamOrWriter

java.lang back to summary

private Class Throwable.SentinelHolder

extends Object
Class Inheritance

Holder class to defer initializing sentinel objects only used for serialization.

Field Summary

Modifier and TypeField and Description
public static final StackTraceElement
STACK_TRACE_ELEMENT_SENTINEL

Setting the stack trace to a one-element array containing this sentinel value indicates future attempts to set the stack trace will be ignored.

public static final StackTraceElement[]
STACK_TRACE_SENTINEL

Sentinel value used in the serial form to indicate an immutable stack trace.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

STACK_TRACE_ELEMENT_SENTINELback to summary
public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL

Setting the stack trace to a one-element array containing this sentinel value indicates future attempts to set the stack trace will be ignored. The sentinel is equal to the result of calling:
new StackTraceElement("", "", null, Integer.MIN_VALUE)

STACK_TRACE_SENTINELback to summary
public static final StackTraceElement[] STACK_TRACE_SENTINEL

Sentinel value used in the serial form to indicate an immutable stack trace.

Constructor Detail

SentinelHolderback to summary
private SentinelHolder()
java.lang back to summary

private Class Throwable.WrappedPrintStream

extends PrintStreamOrWriter
Class Inheritance

Field Summary

Modifier and TypeField and Description
private final PrintStream

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
pack-priv Object
lock()

Implements abstract java.lang.Throwable.PrintStreamOrWriter.lock.

Returns the object to be locked when using this StreamOrWriter

pack-priv void
println(Object o)

Implements abstract java.lang.Throwable.PrintStreamOrWriter.println.

Prints the specified string as a line on this StreamOrWriter

Inherited from java.lang.Throwable.PrintStreamOrWriter:
isLockedByCurrentThread

Field Detail

printStreamback to summary
private final PrintStream printStream

Constructor Detail

WrappedPrintStreamback to summary
pack-priv WrappedPrintStream(PrintStream printStream)

Method Detail

lockback to summary
pack-priv Object lock()

Implements abstract java.lang.Throwable.PrintStreamOrWriter.lock.

Doc from java.lang.Throwable.PrintStreamOrWriter.lock.

Returns the object to be locked when using this StreamOrWriter

printlnback to summary
pack-priv void println(Object o)

Implements abstract java.lang.Throwable.PrintStreamOrWriter.println.

Doc from java.lang.Throwable.PrintStreamOrWriter.println.

Prints the specified string as a line on this StreamOrWriter

java.lang back to summary

private Class Throwable.WrappedPrintWriter

extends PrintStreamOrWriter
Class Inheritance

Field Summary

Modifier and TypeField and Description
private final PrintWriter

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
pack-priv Object
lock()

Implements abstract java.lang.Throwable.PrintStreamOrWriter.lock.

Returns the object to be locked when using this StreamOrWriter

pack-priv void
println(Object o)

Implements abstract java.lang.Throwable.PrintStreamOrWriter.println.

Prints the specified string as a line on this StreamOrWriter

Inherited from java.lang.Throwable.PrintStreamOrWriter:
isLockedByCurrentThread

Field Detail

printWriterback to summary
private final PrintWriter printWriter

Constructor Detail

WrappedPrintWriterback to summary
pack-priv WrappedPrintWriter(PrintWriter printWriter)

Method Detail

lockback to summary
pack-priv Object lock()

Implements abstract java.lang.Throwable.PrintStreamOrWriter.lock.

Doc from java.lang.Throwable.PrintStreamOrWriter.lock.

Returns the object to be locked when using this StreamOrWriter

printlnback to summary
pack-priv void println(Object o)

Implements abstract java.lang.Throwable.PrintStreamOrWriter.println.

Doc from java.lang.Throwable.PrintStreamOrWriter.println.

Prints the specified string as a line on this StreamOrWriter