Java Reference
In-Depth Information
information on the console. The
getStackTrace()
method provides programmatic access
to the stack trace information printed by
printStackTrace()
.
Listing 14.6 gives an example that uses the methods in
Throwable
to display exception
information. Line 4 invokes the
sum
method to return the sum of all the elements in the array.
There is an error in line 23 that causes the
ArrayIndexOutOfBoundsException
, a sub-
class of
IndexOutOfBoundsException
. This exception is caught in the
try-catch
block.
Lines 7, 8, and 9 display the stack trace, exception message, and exception object and mes-
sage using the
printStackTrace()
,
getMessage()
, and
toString()
methods, as
shown in Figure 14.5. Line 12 brings stack trace elements into an array. Each element repre-
sents a method call. You can obtain the method (line 14), class name (line 15), and exception
line number (line 16) for each element.
printStackTrace()
getMessage()
toString()
Using
getStackTrace()
F
IGURE
14.5
You can use the
printStackTrace()
,
getMessage()
,
toString()
, and
getStackTrace()
methods to obtain information from exception objects.
L
ISTING
14.6
TestException.java
1
public class
TestException {
2
public static void
main(String[] args) {
3
try
{
4 System.out.println(
sum(
new int
[] {
1
,
2
,
3
,
4
,
5
})
);
invoke
sum
5 }
6
catch
(Exception ex) {
7 ex.printStackTrace();
8 System.out.println(
"\n"
+ ex.getMessage());
9 System.out.println(
"\n"
+ ex.toString());
10
11 System.out.println(
"\nTrace Info Obtained from getStackTrace"
);
12 StackTraceElement[] traceElements = ex.getStackTrace();
13
for
(
int
i =
0
; i < traceElements.length; i++) {
14 System.out.print(
"method "
+ traceElements[i].getMethodName());
15 System.out.print(
"("
+ traceElements[i].getClassName() +
":"
);
16 System.out.println(traceElements[i].getLineNumber() +
")"
);
17 }
18 }
19 }
20
21
printStackTrace()
getMessage()
toString()
private static int
sum(
int
[] list) {
22
int
result =
0
;
i <= list.length
23
for
(
int
i =
0
;
; i++)