Java Reference
In-Depth Information
METHOD DESCRIPTION
getMessage()
This returns the contents of the message, describing the current exception. This is typically the
fully qualified name of the exception class (it is a subclass of
Throwable
) and a brief description
of the exception.
getCause()
Returns the
Throwable
that records the cause for this exception. This will typically be the excep-
tion that caused this exception to be thrown.
printStackTrace()
This outputs the message and the stack trace to the standard error output stream — which is the
screen in the case of a console program.
This is the same as the previous method except that you specify the output stream as an argu-
ment. Calling the previous method for an exception object
e
is equivalent to
e.printStackTrace(System.err);
printStackTrace
(PrintStream s)
You can get the stack trace as an array of
StackTraceElement
references by calling
getStackTrace()
for a
Throwable
object. Each
StackTraceElement
object records information about the execution point in a
method when the exception was thrown. There will be a
StackTraceElement
array element for each meth-
od in the call stack when the exception was thrown. The following
StackTraceElement
methods provide
you with details of a stack trace entry:
•
getClassName()
returns the fully qualified name of the class containing the execution point for
this stack trace entry.
•
getFileName()
returns the name of the source file containing the execution point.
•
getLineNumber()
returns the line number for the execution point in the source file.
•
getMethodName()
returns the name of the method containing the execution point.
Another
Throwable
method,
fillInStackTrace()
, updates the stack trace to the point at which this
method is called. For example, if you put a call to this method in the
catch
block
e.fillInStackTrace();
the line number recorded in the stack record for the method in which the exception occurs is the line where
fillInStackTrace()
is called. The main use of this is when you want to rethrow an exception (so it is
caught by the calling method) and record the point at which it is rethrown. For example:
e.fillInStackTrace(); // Record the throw point
throw e; // Rethrow the exception
In practice, it's often more useful to throw an exception of your own that encapsulates the exception that
caused your exception to be thrown. This is referred to as
exception chaining
. You see how to define your
own exceptions in the next section and use chained exceptions, but first, let's exercise some of the methods
defined in the
Throwable
class and see the results.
TRY IT OUT: Dishing the Dirt on Exceptions
The easiest way to try out some of the methods I've just discussed is to make some changes to the
catch
blocks in the
divide()
method you have in the
TryBlockTest
class example. I make the class for this
example
TryBlockTest2
. The
main()
method is the same as for
TryBlockTest
. Here's the modified
version of
divide()
: