Java Reference
In-Depth Information
The Class Throwable
The class Throwable is the class from which all Java exception classes are derived - that is, every
exception object will contain the methods defined in this class. The class Throwable has two
constructors, a default constructor, and a constructor that accepts an argument of type String . The
String object that is passed to the constructor is used to provide a description of the nature of the
problem causing the exception. Both constructors are public .
Objects of type Throwable contain two items of information about an exception:
A message, that we have just referred to as being initialized by a constructor
A record of the execution stack at the time the object was created
The execution stack keeps track of all the methods that are in execution at any given instant. It provides
the means whereby executing a return gets back to the calling point for a method. The record of the
execution stack that is stored in the exception object will consist of the line number in the source code
where the exception originated followed by a trace of the method calls that immediately preceded the
point at which the exception occurred. This is made up of the fully qualified name for each of the
methods called, plus the line number in the source file where each method call occurred. The method
calls are in sequence with the most recent method call appearing first. This will help you to understand
how this point in the program was reached.
The Throwable class has the following public methods that enable you to access the message and
the stack trace:
Method
Description
getMessage()
This returns the contents of the message, describing the current
exception. This will typically be the fully qualified name of the
exception class (it will be a subclass of Throwable ), and a brief
description of the exception.
printStackTrace()
This will output the message and the stack trace to the standard error
output stream - which is the screen in the case of a console program.
printStackTrace
(PrintStream s)
This is the same as the previous method except that you specify the
output stream as an argument. Calling the previous method for an
exception object, e , is equivalent to:
e.printStackTrace(System.err);
There's another method, fillInStackTrace() , which will update 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 occurred will be the line
where fillInStackTrace() is called. The main use of this is when you want to rethrow an exception (so
it will be caught by the calling method) and record the point at which it is rethrown. For example:
Search WWH ::




Custom Search