Java Reference
In-Depth Information
cause is created by invoking the Throwable(Throwable cause) or Throw-
able(String message, Throwable cause) constructor, which invoke the
initCause() methodtostorethecause.Ifyoudonotcalleitherconstructor,youcan
alternativelycall initCause() directly,butmustdosoimmediatelyaftercreatingthe
throwable. Call the getCause() method to return the cause.
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
connectionbetweenthetwoexceptions.Incontrast,therearesituationswheretwoinde-
pendentexceptionscanbethrowninsiblingcodeblocks;forexample,inthetryblock
ofatry-with-resourcesstatement(discussedlaterinthischapter)andthecompiler-gen-
eratedfinallyblockthatclosestheresource.Inthesesituations,onlyoneofthethrown
exceptions can be propagated.
In the try-with-resources statement, when there are two such exceptions, the excep-
tionoriginatingfromthetryblockispropagatedandtheexceptionfromthefinallyblock
isadded(viathe addSuppressed() method)tothelistofexceptions suppressed by
theexceptionfromthetryblock.Asanexceptionunwindsthestack,itcanaccumulate
multiplesuppressedexceptions.Anarrayofthesuppressedexpressionscanberetrieved
by calling getSuppressed() .
When an exception is thrown, it leaves behind a stack of unfinished method calls.
Throwable 'sconstructorscall fillInStackTrace() torecordthis stack trace in-
formation, which is output by calling printStackTrace() .
The getStackTrace() method provides programmatic access to the stack trace
byreturningthisinformationasanarrayof java.lang.StackTraceElement in-
stances - each instance represents one stack entry. StackTraceElement provides
methods to return stack trace information. For example, String getMeth-
odName() returns the name of an unfinished method.
The setStackTrace() method is designed for use by Remote Procedure Call
(RPC) frameworks (RPC is briefly discussed in Chapter 11 ) and other advanced sys-
tems, allowing the client to override the default stack trace that is generated by
fillInStackTrace() when a throwable is constructed, or deserialized when a
throwable is read from a serialization stream. (I will discuss serialization in Chapter 8 . )
Exceptfor Throwable(String message, Throwable cause, boolean
enableSuppression, boolean writableStackTrace) , each Throw-
able constructor always treats suppression as being enabled, and always calls
fillInStackTrace() . In contrast, this constructor lets you disable suppression
bypassing false to enableSuppression ,andprevent fillInStackTrace()
Search WWH ::




Custom Search