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.
and
java.
, 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).
Modifier and Type | Class and Description |
---|---|
private abstract static class | Throwable.
Wrapper class for PrintStream and PrintWriter to enable a single implementation of printStackTrace. |
private static class | Throwable.
Holder class to defer initializing sentinel objects only used for serialization. |
private static class | |
private static class |
Modifier and Type | Field 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 |
private static final String | SUPPRESSED_CAPTION
Caption for labeling suppressed exception stack traces |
private static final List | |
private List | suppressedExceptions
The list of suppressed exceptions, as returned by |
private static final StackTraceElement[] | UNASSIGNED_STACK
A shared value for an empty stack. |
Access | Constructor and Description |
---|---|
public | |
public | Throwable(String
the detail message. The detail message is saved for
later retrieval by the message)getMessage() method.Constructs a new throwable with the specified detail message. |
public | Throwable(String
the detail message (which is saved for later retrieval
by the message, Throwable getMessage() method).the cause (which is saved for later retrieval by the
cause)getCause() method). (A null value is
permitted, and indicates that the cause is nonexistent or
unknown.)Constructs a new throwable with the specified detail message and cause. |
public | Throwable(Throwable
the cause (which is saved for later retrieval by the
cause)getCause() method). (A null value is
permitted, and indicates that the cause is nonexistent or
unknown.)Constructs a new throwable with the specified cause and a detail
message of |
protected | Throwable(String
the detail message. message, Throwable the cause. (A cause, boolean null value is permitted,
and indicates that the cause is nonexistent or unknown.)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. |
Modifier and Type | Method 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 thisThrowable instance.Fills in the execution stack trace. |
private native Throwable | |
public synchronized Throwable | Returns: the cause of this throwable ornull if the
cause is nonexistent or unknown.Returns the cause of this throwable or |
public String | Returns: The localized description of this throwable.Creates a localized description of this throwable. |
public String | Returns: the detail message string of thisThrowable instance
(which may be null ).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.Provides programmatic access to the stack trace information printed by
|
public final synchronized Throwable[] | Returns: an array containing all of the exceptions that were suppressed to deliver this exception.Returns an array containing all of the exceptions that were
suppressed, typically by the |
public synchronized Throwable | Returns: a reference to thisThrowable instance.the cause (which is saved for later retrieval by the
cause)getCause() method). (A null value is
permitted, and indicates that the cause is nonexistent or
unknown.)Initializes the cause of this throwable to the specified value. |
private void | |
private void | printEnclosedStackTrace(Throwable.
Print our stack trace as an enclosed exception for the specified stack trace. |
public void | |
public void | printStackTrace(PrintStream
PrintStream to use for outputPrints this throwable and its backtrace to the specified print stream. |
private void | |
public void | printStackTrace(PrintWriter
PrintWriter to use for outputPrints this throwable and its backtrace to the specified print writer. |
private void | readObject(ObjectInputStream
the s)ObjectInputStream from which data is readReads a |
pack-priv final void | |
public void | setStackTrace(StackTraceElement[]
the stack trace elements to be associated with
this stackTrace)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.Sets the stack trace elements that will be returned by
|
public String | Returns: a string representation of this throwable.Overrides java. Returns a short description of this throwable. |
private int | |
private synchronized void | writeObject(ObjectOutputStream
the s)ObjectOutputStream to which data is writtenWrite a |
backtrace | back to summary |
---|---|
private transient Object backtrace The JVM saves some indication of the stack backtrace in this slot. |
cause | back 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.
|
CAUSE_CAPTION | back to summary |
---|---|
private static final String CAUSE_CAPTION Caption for labeling causative exception stack traces |
depth | back to summary |
---|---|
private transient int depth The JVM code sets the depth of the backtrace for later retrieval |
detailMessage | back to summary |
---|---|
private String detailMessage Specific details about the Throwable. For example, for
|
EMPTY_THROWABLE_ARRAY | back to summary |
---|---|
private static final Throwable[] EMPTY_THROWABLE_ARRAY |
jfrTracing | back 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_MESSAGE | back to summary |
---|---|
private static final String NULL_CAUSE_MESSAGE Message for trying to suppress a null exception. |
SELF_SUPPRESSION_MESSAGE | back to summary |
---|---|
private static final String SELF_SUPPRESSION_MESSAGE Message for trying to suppress oneself. |
serialVersionUID | back to summary |
---|---|
private static final long serialVersionUID use serialVersionUID from JDK 1.0.2 for interoperability |
stackTrace | back to summary |
---|---|
private StackTraceElement[] stackTrace The stack trace, as returned by
|
SUPPRESSED_CAPTION | back to summary |
---|---|
private static final String SUPPRESSED_CAPTION Caption for labeling suppressed exception stack traces |
SUPPRESSED_SENTINEL | back to summary |
---|---|
private static final List<Throwable> SUPPRESSED_SENTINEL |
suppressedExceptions | back to summary |
---|---|
private List<Throwable> suppressedExceptions The list of suppressed exceptions, as returned by
|
UNASSIGNED_STACK | back to summary |
---|---|
private static final StackTraceElement[] UNASSIGNED_STACK A shared value for an empty stack. |
Throwable | back to summary |
---|---|
public Throwable() Constructs a new throwable with The
|
Throwable | back 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 The
|
Throwable | back 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
The
|
Throwable | back to summary |
---|---|
public Throwable(Throwable cause) Constructs a new throwable with the specified cause and a detail
message of The
|
Throwable | back 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, Note that the other constructors of
|
addSuppressed | back 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 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 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.
|
fillInStackTrace | back to summary |
---|---|
public synchronized Throwable fillInStackTrace() Fills in the execution stack trace. This method records within this
If the stack trace of this
|
fillInStackTrace | back to summary |
---|---|
private native Throwable fillInStackTrace(int dummy) |
getCause | back to summary |
---|---|
public synchronized Throwable getCause() Returns the cause of this throwable or This implementation returns the cause that was supplied via one of
the constructors requiring a
|
getLocalizedMessage | back 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 | back to summary |
---|---|
public String getMessage() Returns the detail message string of this throwable.
|
getOurStackTrace | back to summary |
---|---|
private synchronized StackTraceElement[] getOurStackTrace() |
getStackTrace | back to summary |
---|---|
public StackTraceElement[] getStackTrace() Provides programmatic access to the stack trace information printed by
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
|
getSuppressed | back to summary |
---|---|
public final synchronized Throwable[] getSuppressed() Returns an array containing all of the exceptions that were
suppressed, typically by the
|
initCause | back 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 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 }
|
lockedPrintStackTrace | back to summary |
---|---|
private void lockedPrintStackTrace(Throwable. |
printEnclosedStackTrace | back to summary |
---|---|
private void printEnclosedStackTrace(Throwable. Print our stack trace as an enclosed exception for the specified stack trace. |
printStackTrace | back to summary |
---|---|
public void printStackTrace() Prints this throwable and its backtrace to the
standard error stream. This method prints a stack trace for this
This example was produced by running the program:java.lang.NullPointerException at MyClass.mash(MyClass.java:9) at MyClass.crunch(MyClass.java:6) at MyClass.main(MyClass.java:3) 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 moreNote 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 moreNote 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 |
printStackTrace | back to summary |
---|---|
public void printStackTrace(PrintStream s) Prints this throwable and its backtrace to the specified print stream.
|
printStackTrace | back to summary |
---|---|
private void printStackTrace(Throwable. |
printStackTrace | back to summary |
---|---|
public void printStackTrace(PrintWriter s) Prints this throwable and its backtrace to the specified print writer.
|
readObject | back to summary |
---|---|
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException Reads a
|
setCause | back to summary |
---|---|
pack-priv final void setCause(Throwable t) |
setStackTrace | back to summary |
---|---|
public void setStackTrace(StackTraceElement[] stackTrace) Sets the stack trace elements that will be returned by
If the stack trace of this
|
toString | back to summary |
---|---|
public String toString() Overrides java. Returns a short description of this throwable. The result is the concatenation of:
getLocalizedMessage returns null , then just
the class name is returned.
|
validateSuppressedExceptionsList | back to summary |
---|---|
private int validateSuppressedExceptionsList(List<Throwable> deserSuppressedExceptions) throws IOException |
writeObject | back to summary |
---|---|
private synchronized void writeObject(ObjectOutputStream s) throws IOException Write a
|
Access | Constructor and Description |
---|---|
private |
Modifier and Type | Method and Description |
---|---|
pack-priv boolean | |
pack-priv abstract Object | |
pack-priv abstract void |
PrintStreamOrWriter | back to summary |
---|---|
private PrintStreamOrWriter() |
isLockedByCurrentThread | back to summary |
---|---|
pack-priv boolean isLockedByCurrentThread() |
lock | back to summary |
---|---|
pack-priv abstract Object lock() Returns the object to be locked when using this StreamOrWriter |
println | back to summary |
---|---|
pack-priv abstract void println(Object o) Prints the specified string as a line on this StreamOrWriter |
Modifier and Type | Field 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. |
Access | Constructor and Description |
---|---|
private |
STACK_TRACE_ELEMENT_SENTINEL | back 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: |
STACK_TRACE_SENTINEL | back to summary |
---|---|
public static final StackTraceElement[] STACK_TRACE_SENTINEL Sentinel value used in the serial form to indicate an immutable stack trace. |
SentinelHolder | back to summary |
---|---|
private SentinelHolder() |
Modifier and Type | Field and Description |
---|---|
private final PrintStream |
Access | Constructor and Description |
---|---|
pack-priv |
Modifier and Type | Method and Description |
---|---|
pack-priv Object | lock()
Implements abstract java. Returns the object to be locked when using this StreamOrWriter |
pack-priv void | println(Object o)
Implements abstract java. Prints the specified string as a line on this StreamOrWriter |
printStream | back to summary |
---|---|
private final PrintStream printStream |
WrappedPrintStream | back to summary |
---|---|
pack-priv WrappedPrintStream(PrintStream printStream) |
lock | back to summary |
---|---|
pack-priv Object lock() Implements abstract java. Doc from java. Returns the object to be locked when using this StreamOrWriter |
println | back to summary |
---|---|
pack-priv void println(Object o) Implements abstract java. Doc from java. Prints the specified string as a line on this StreamOrWriter |
Modifier and Type | Field and Description |
---|---|
private final PrintWriter |
Access | Constructor and Description |
---|---|
pack-priv |
Modifier and Type | Method and Description |
---|---|
pack-priv Object | lock()
Implements abstract java. Returns the object to be locked when using this StreamOrWriter |
pack-priv void | println(Object o)
Implements abstract java. Prints the specified string as a line on this StreamOrWriter |
printWriter | back to summary |
---|---|
private final PrintWriter printWriter |
WrappedPrintWriter | back to summary |
---|---|
pack-priv WrappedPrintWriter(PrintWriter printWriter) |
lock | back to summary |
---|---|
pack-priv Object lock() Implements abstract java. Doc from java. Returns the object to be locked when using this StreamOrWriter |
println | back to summary |
---|---|
pack-priv void println(Object o) Implements abstract java. Doc from java. Prints the specified string as a line on this StreamOrWriter |