Java Reference
In-Depth Information
Analyze the output from the exception's printStackTrace() method:
try {
int a = 5/0;
} catch (Exception e) {
e.printStackTrace();
}
Result:
java.lang.ArithmeticException: / by zero
at
org.java8recipes.chapter11.recipe11_01.Recipe11_1.start(Recipe11_1.java:18)
at
org.java8recipes.chapter11.recipe11_01.Recipe11_1.main(Recipe11_1.java:13)
How It Works
In programming lingo, a stack refers to the list of functions that were called to get to a
point in your program, usually starting from the immediate ( Sys-
tem.out.println() ) to the more general ( public static void main ).
Every program keeps track of which code was executed in order to reach a specific part
of the code. Stack trace's output refers to the stack that was in memory when an error
occurred. Exceptions thrown in Java keep track of where they occurred and which code
path was executed when the exception was thrown. Stack trace shows from the most
specific place where the exception happened (the line where the exception occurred) to
the top-level invoker of the offending code (and everything in between). This informa-
tion then allows you to pinpoint which method calls were performed, and may help
shed some light on why the exception was thrown.
In this example, the divide-by-zero exception occurred on line 18 of Re-
cipe11_1.java and was caused by a call from the main() method (at line 13).
Sometimes, when looking at the stack trace's output , you will see methods that don't
belong to the project. This happens naturally as sometimes method calls are generated
in other parts of a working system. It is, for example, very common to see AWT meth-
ods in Swing applications when an exception is raised (due to the nature of the
EventQueue ). If you look at the more specific function calls (earliest), you will
Search WWH ::




Custom Search