Java Reference
In-Depth Information
method
main
catches the thrown object. The statement in Line 7 outputs the appropriate
message. Notice that the output of the statement in Line 16 (the second line of the sample
run) does not output the string
getNumber
, whereas the statement in Line 7 (the third
line of the sample run) does output the string
getNumber
. This is because the statement
in Line 17 creates and throws an object that is different from the
InputMismatchException
object thrown by the statement in Line 12. The message
string of the object thrown by the statement in Line 12 is null; the object thrown by the
statement in Line 17 contains the message string
"getNumber"
.
The programs in Examples 11-7 and 11-8 illustrate how a method can rethrow the same
exception object, or create an exception object and throw it for the calling method to
handle. This mechanism is quite useful; it allows a program to handle all the exceptions in
one location rather than spreading exception-handling code throughout the program.
Suppose that method
A
calls method
B
, method
B
calls method
C
, and an exception occurs
in method
C
. Java keeps track of this sequence of method calls. Recall that the
class
Exception
is a subclass of the
class
Throwable
. As shown in Table 11-1, the
class
Throwable
contains the
public
method
printStackTrace
. Because the method
printStackTrace
is
public
, every subclass of the
class
Throwable
inherits this
method. When an exception occurs in a method, you can use the method
printStackTrace
to determine the order in which the methods were called and where
the exception was handled.
EXAMPLE 11-9
1
1
This example shows the use of the method
printStackTrace
to show the order in
which methods are called and exceptions handled.
import
java.io.*;
public class
PrintStackTraceExample1
{
public static void
main(String[] args)
{
try
{
methodA();
}
catch
(Exception e)
{
System.out.println(e.toString() + " caught in main");
e.printStackTrace();
}
}
Search WWH ::
Custom Search