Java Reference
In-Depth Information
Division by 0 is not defined, so the attempt to divide by 0 is an error. Java han-
dles this error by throwing an exception , which causes the program to terminate
abnormally with the following messages in the Java console:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Ex.main(
(The first part of the first line, which says that an exception occurred in thread
main, may be missing.) The important information on the first line is that an
ArithmeticException occurred, a division by zero. The second line says where
the exception occurred: in method main of class Ex , on line three of file .
The information following the second line (if present) is not important for
understanding the reason for program termination, and you can disregard it.
The call-stack trace
When the program aborts because of an exception, you have to study it to
find out why and correct the error. The messages in the Java console tell you the
kind of Exception that occurred and the method being executed at the time, and
this can be helpful. But the Java console contains more. To illustrate, we change
the program so that the division by 0 occurs within a different method:
public class Ex {
public static void main(String[] args)
{ first(); }
public static void first()
{ second(); }
public static void second()
{ System.out.println(5 / 0); }
Suppose method main is called. Method main calls method first , which
calls method second , which attempts to divide by 0 .
This list of calls that have been started but have not completed is called the
call stack . When the attempt to divide by zero occurs, the same exception is
thrown, and the following appears in the Java console:
java.lang.ArithmeticException: / by zero
at Ex.second(
at Ex.first(
at Ex.main(
As before, the first line says that an ArithmeticException occurred, a division
by zero. The second line says that the Exception occurred in method second , at
line seven of file . The third line says that method second was called
from method first , and the fourth line says that first was called from main .
Thus, when an Exception occurs:
Search WWH ::

Custom Search