Java Reference
In-Depth Information
public static void
methodA()
throws
Exception
{
methodB();
}
public static void
methodB()
throws
Exception
{
methodC();
}
public static void
methodC()
throws
Exception
{
throw new
Exception("Exception generated in method C");
}
}
Sample Run:
java.lang.Exception: Exception generated in method C caught in main
java.lang.Exception: Exception generated in method C
at PrintStackTraceExample1.methodC(PrintStackTraceExample1.java:30)
at PrintStackTraceExample1.methodB(PrintStackTraceExample1.java:25)
at PrintStackTraceExample1.methodA(PrintStackTraceExample1.java:20)
at PrintStackTraceExample1.main(PrintStackTraceExample1.java:9)
The preceding program contains the methods
methodA
,
methodB
,
methodC
,and
main
.The
method
methodC
creates and throws an object of the
class
Exception
.Themethod
methodB
calls
methodC
,
methodA
calls
methodB
, and the method
main
calls
methodA
.
Because the methods
methodA
and
methodB
do not handle the exception thrown by
methodC
, they contain the
throws
Exception
clause in their heading. The method
main
handles the exception thrown by
methodC
, which was propagated first by
methodB
and then
by
methodA
.The
catch
block in the method
main
first outputs the message contained in the
exception object and the string
" caught in main"
, then it calls the method
printStackTrace
to trace the method calls (see the last four lines of the output).
The program in Example 11-10 is similar to the program in Example 11-9. The main
difference is that the exception thrown by
methodC
is caught and handled in
methodA
.
Note that the heading of
methodA
does not contain any
throws
clause.
EXAMPLE 11-10
import
java.io.*;
public class
PrintStackTraceExample2
{
public static void
main(String[] args)
{
methodA();
}
Search WWH ::
Custom Search