Class Throwable
- All Implemented Interfaces:
Serializable
Throwable class is the superclass of all errors andexceptions in the Java language. Only objects that are instances of thisclass (or one of its subclasses) are thrown by the Java Virtual Machine orcan be thrown by the Javathrow statement. Similarly, onlythis class or one of its subclasses can be the argument type in acatch clause.For the purposes of compile-time checking of exceptions,Throwable and any subclass ofThrowable that is not also asubclass of eitherRuntimeException orError areregarded as checked exceptions.Instances of two subclasses,Error andException, are conventionally used to indicatethat exceptional situations have occurred. Typically, these instancesare freshly created in the context of the exceptional situation soas to include relevant information (such as stack trace data).
A throwable contains a snapshot of the execution stack of itsthread at the time it was created. It can also contain a messagestring that gives more information about the error. Over time, athrowable cansuppress otherthrowables from being propagated. Finally, the throwable can alsocontain acause: another throwable that caused thisthrowable to be constructed. The recording of this causal informationis referred to as thechained exception facility, as thecause can, itself, have a cause, and so on, leading to a "chain" ofexceptions, each caused by another.
One reason that a throwable may have a cause is that the class thatthrows it is built atop a lower layered abstraction, and an operation onthe upper layer fails due to a failure in the lower layer. It would be baddesign to let the throwable thrown by the lower layer propagate outward, asit 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 ofits implementation, assuming the lower layer's exception was a checkedexception. Throwing a "wrapped exception" (i.e., an exception containing acause) allows the upper layer to communicate the details of the failure toits caller without incurring either of these shortcomings. It preservesthe flexibility to change the implementation of the upper layer withoutchanging its API (in particular, the set of exceptions thrown by itsmethods).
A second reason that a throwable may have a cause is that the methodthat throws it must conform to a general-purpose interface that does notpermit the method to throw the cause directly. For example, supposea persistent collection conforms to theCollection interface, and that its persistence is implemented atopjava.io. Suppose the internals of theadd methodcan throw anIOException. The implementationcan communicate the details of theIOException to its callerwhile conforming to theCollection interface by wrapping theIOException in an appropriate unchecked exception. (Thespecification for the persistent collection should indicate that it iscapable of throwing such exceptions.)
A cause can be associated with a throwable in two ways: via aconstructor that takes the cause as an argument, or via theinitCause(Throwable) method. New throwable classes thatwish to allow causes to be associated with them should provide constructorsthat take a cause and delegate (perhaps indirectly) to one of theThrowable constructors that takes a cause.Because theinitCause method is public, it allows a cause to beassociated with any throwable, even a "legacy throwable" whoseimplementation predates the addition of the exception chaining mechanism toThrowable.
By convention, classThrowable and its subclasses have twoconstructors, one that takes no arguments and one that takes aString argument that can be used to produce a detail message.Further, those subclasses that might likely have a cause associated withthem should have two more constructors, one that takes aThrowable (the cause), and one that takes aString (the detail message) and aThrowable (thecause).
- SeeJava Language Specification:
- 11.2 Compile-Time Checking of Exceptions
- Since:
- 1.0
- See Also:
Constructor Summary
ConstructorsModifierConstructorDescriptionConstructs a new throwable withnullas its detail message.Constructs a new throwable with the specified detail message.Constructs a new throwable with the specified detail message andcause.protectedConstructs a new throwable with the specified detail message,cause,suppression enabled ordisabled, and writable stack trace enabled or disabled.Constructs a new throwable with the specified cause and a detailmessage of(cause==null ? null : cause.toString())(whichtypically contains the class and detail message ofcause).Method Summary
Modifier and TypeMethodDescriptionfinal voidaddSuppressed(Throwable exception) Appends the specified exception to the exceptions that weresuppressed in order to deliver this exception.Fills in the execution stack trace.getCause()Returns the cause of this throwable ornullif thecause is nonexistent or unknown.Creates a localized description of this throwable.Returns the detail message string of this throwable.Provides programmatic access to the stack trace information printed byprintStackTrace().finalThrowable[]Returns an array containing all of the exceptions that weresuppressed, typically by thetry-with-resourcesstatement, in order to deliver this exception.Initializes thecause of this throwable to the specified value.voidPrints this throwable and its backtrace to thestandard error stream.voidPrints this throwable and its backtrace to the specified print stream.voidPrints this throwable and its backtrace to the specifiedprint writer.voidsetStackTrace(StackTraceElement[] stackTrace) Sets the stack trace elements that will be returned bygetStackTrace()and printed byprintStackTrace()and related methods.toString()Returns a short description of this throwable.
Constructor Details
Throwable
public Throwable()Constructs a new throwable withnullas its detail message.The cause is not initialized, and may subsequently be initialized by acall toinitCause(Throwable).The
fillInStackTrace()method is called to initializethe stack trace data in the newly created throwable.Throwable
Constructs a new throwable with the specified detail message. Thecause is not initialized, and may subsequently be initialized bya call toinitCause(Throwable).The
fillInStackTrace()method is called to initializethe stack trace data in the newly created throwable.- Parameters:
message- the detail message. The detail message is saved for later retrieval by thegetMessage()method.
Throwable
Constructs a new throwable with the specified detail message andcause.Note that the detail message associated with
causeisnot automatically incorporated inthis throwable's detail message.The
fillInStackTrace()method is called to initializethe stack trace data in the newly created throwable.- Parameters:
message- the detail message (which is saved for later retrieval by thegetMessage()method).cause- the cause (which is saved for later retrieval by thegetCause()method). (Anullvalue is permitted, and indicates that the cause is nonexistent or unknown.)- Since:
- 1.4
Throwable
Constructs a new throwable with the specified cause and a detailmessage of(cause==null ? null : cause.toString())(whichtypically contains the class and detail message ofcause).This constructor is useful for throwables that are little more thanwrappers for other throwables (for example,PrivilegedActionException).The
fillInStackTrace()method is called to initializethe stack trace data in the newly created throwable.- Parameters:
cause- the cause (which is saved for later retrieval by thegetCause()method). (Anullvalue is permitted, and indicates that the cause is nonexistent or unknown.)- Since:
- 1.4
Throwable
protected Throwable(String message,Throwable cause, boolean enableSuppression, boolean writableStackTrace) Constructs a new throwable with the specified detail message,cause,suppression enabled ordisabled, and writable stack trace enabled or disabled. Ifsuppression is disabled,getSuppressed()for this objectwill return a zero-length array and calls toaddSuppressed(Throwable)that would otherwise append an exception to thesuppressed list will have no effect. If the writable stacktrace is false, this constructor will not callfillInStackTrace(), anullwill be written to thestackTracefield, and subsequent calls tofillInStackTraceandsetStackTrace(StackTraceElement[])will not set the stacktrace. If the writable stack trace is false,getStackTrace()will return a zero length array.Note that the other constructors of
Throwabletreatsuppression as being enabled and the stack trace as beingwritable. Subclasses ofThrowableshould document anyconditions under which suppression is disabled and documentconditions under which the stack trace is not writable.Disabling of suppression should only occur in exceptionalcircumstances where special requirements exist, such as avirtual machine reusing exception objects under low-memorysituations. Circumstances where a given exception object isrepeatedly caught and rethrown, such as to implement controlflow between two sub-systems, is another situation whereimmutable throwable objects would be appropriate.- Parameters:
message- the detail message.cause- the cause. (Anullvalue is permitted,and indicates that the cause is nonexistent or unknown.)enableSuppression- whether or not suppression is enabledwritableStackTrace- whether or not the stack trace is writable- Since:
- 1.7
- See Also:
Method Details
getMessage
Returns the detail message string of this throwable.- Returns:
- the detail message string of this
Throwableinstance (which may benull).
getLocalizedMessage
Creates a localized description of this throwable.Subclasses may override this method in order to produce alocale-specific message. For subclasses that do not override thismethod, the default implementation returns the same result asgetMessage().- Returns:
- The localized description of this throwable.
- Since:
- 1.1
getCause
Returns the cause of this throwable ornullif thecause is nonexistent or unknown. (The cause is the throwable thatcaused this throwable to get thrown.)This implementation returns the cause that was supplied via one ofthe constructors requiring a
Throwable, or that was set aftercreation with theinitCause(Throwable)method. While it istypically unnecessary to override this method, a subclass can overrideit to return a cause set by some other means. This is appropriate fora "legacy chained throwable" that predates the addition of chainedexceptions toThrowable. Note that it isnotnecessary to override any of thePrintStackTracemethods,all of which invoke thegetCausemethod to determine thecause of a throwable.- Returns:
- the cause of this throwable or
nullif the cause is nonexistent or unknown. - Since:
- 1.4
initCause
Initializes thecause 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 fromwithin the constructor, or immediately after creating thethrowable. If this throwable was createdwith
Throwable(Throwable)orThrowable(String,Throwable), this method cannot be calledeven once.An example of using this method on a legacy throwable typewithout other support for setting the cause is:
try { lowLevelOp();} catch (LowLevelException le) { throw (HighLevelException) new HighLevelException().initCause(le); // Legacy constructor}- Parameters:
cause- the cause (which is saved for later retrieval by thegetCause()method). (Anullvalue is permitted, and indicates that the cause is nonexistent or unknown.)- Returns:
- a reference to this
Throwableinstance. - Throws:
IllegalArgumentException- ifcauseis this throwable. (A throwable cannot be its own cause.)IllegalStateException- if this throwable was created withThrowable(Throwable)orThrowable(String,Throwable), or this method has already been called on this throwable.- Since:
- 1.4
toString
Returns a short description of this throwable.The result is the concatenation of:- thename of the class of this object
- ": " (a colon and a space)
- the result of invoking this object's
getLocalizedMessage()method
getLocalizedMessagereturnsnull, then justthe class name is returned.printStackTrace
public void printStackTrace()Prints this throwable and its backtrace to thestandard error stream. This method prints a stack trace for thisThrowableobject on the error output stream that isthe value of the fieldSystem.err. The first line ofoutput contains the result of thetoString()method forthis object. Remaining lines represent data previously recorded bythe methodfillInStackTrace(). The format of thisinformation depends on the implementation, but the followingexample may be regarded as typical:
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 causeshould generally include the backtrace for the cause. The formatof this information depends on the implementation, but the followingexample 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 moreCaused 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 thisexception matches the indicated number of frames from the bottom of thestack trace of the exception that was caused by this exception (the"enclosing" exception). This shorthand can greatly reduce the lengthof the output in the common case where a wrapped exception is thrownfrom the same method as the "causative exception" is caught. The aboveexample 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 ofsuppressed exceptions (in conjunction with thetry-with-resources statement). Any exceptions that weresuppressed in order to deliver an exception are printed outbeneath the stack trace. The format of this informationdepends on the implementation, but the following example may beregarded 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 exceptionsjust as it is used on causes. Unlike causes, suppressed exceptions areindented beyond their "containing exceptions."An exception can have both a cause and one or more suppressedexceptions:
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
Prints this throwable and its backtrace to the specified print stream.- Parameters:
s-PrintStreamto use for output
printStackTrace
Prints this throwable and its backtrace to the specifiedprint writer.- Parameters:
s-PrintWriterto use for output- Since:
- 1.1
fillInStackTrace
Fills in the execution stack trace. This method records within thisThrowableobject information about the current state ofthe stack frames for the current thread.If the stack trace of this
Throwableis notwritable, calling this method has no effect.- Returns:
- a reference to this
Throwableinstance. - See Also:
getStackTrace
Provides programmatic access to the stack trace information printed byprintStackTrace(). 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 thestack, 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 invocationin the sequence.Some virtual machines may, under some circumstances, omit oneor more stack frames from the stack trace. In the extreme case,a virtual machine that has no stack trace information concerningthis throwable is permitted to return a zero-length array from thismethod. Generally speaking, the array returned by this method willcontain one element for every frame that would be printed by
printStackTrace. Writes to the returned array do notaffect future calls to this method.- Returns:
- an array of stack trace elements representing the stack trace pertaining to this throwable.
- Since:
- 1.4
setStackTrace
Sets the stack trace elements that will be returned bygetStackTrace()and printed byprintStackTrace()and related methods.This method, which is designed for use by RPC frameworks and otheradvanced systems, allows the client to override the defaultstack trace that is either generated byfillInStackTrace()when a throwable is constructed or deserialized when a throwable isread from a serialization stream.If the stack trace of this
Throwableis notwritable, calling this method has no effect other thanvalidating its argument.- Parameters:
stackTrace- the stack trace elements to be associated withthisThrowable. The specified array is copied by thiscall; changes in the specified array after the method invocationreturns will have no effect on thisThrowable's stacktrace.- Throws:
NullPointerException- ifstackTraceisnullor if any of the elements ofstackTracearenull- Since:
- 1.4
addSuppressed
Appends the specified exception to the exceptions that weresuppressed in order to deliver this exception. This method isthread-safe and typically called (automatically and implicitly)by thetry-with-resources statement.The suppression behavior is enabledunless disabledviaa constructor. When suppression is disabled, this method doesnothing other than to validate its argument.
Note that when one exceptioncauses another exception, the firstexception is usually caught and then the second exception isthrown in response. In other words, there is a causalconnection between the two exceptions.In contrast, there are situations where two independentexceptions can be thrown in sibling code blocks, in particularin the
tryblock of atry-with-resourcesstatement and the compiler-generatedfinallyblockwhich closes the resource.In these situations, only one of the thrown exceptions can bepropagated. In thetry-with-resources statement, whenthere are two such exceptions, the exception originating fromthetryblock is propagated and the exception from thefinallyblock is added to the list of exceptionssuppressed by the exception from thetryblock. As anexception unwinds the stack, it can accumulate multiplesuppressed exceptions.An exception may have suppressed exceptions while also beingcaused by another exception. Whether or not an exception has acause is semantically known at the time of its creation, unlikewhether or not an exception will suppress other exceptionswhich is typically only determined after an exception isthrown.
Note that programmer written code is also able to takeadvantage of calling this method in situations where there aremultiple sibling exceptions and only one can be propagated.
- Parameters:
exception- the exception to be added to the list of suppressed exceptions- Throws:
IllegalArgumentException- ifexceptionis this throwable; a throwable cannot suppress itself.NullPointerException- ifexceptionisnull- Since:
- 1.7
getSuppressed
Returns an array containing all of the exceptions that weresuppressed, typically by thetry-with-resourcesstatement, in order to deliver this exception.If no exceptions were suppressed orsuppression isdisabled, an empty array is returned. This method isthread-safe. Writes to the returned array do not affect futurecalls to this method.- Returns:
- an array containing all of the exceptions that were suppressed to deliver this exception.
- Since:
- 1.7