Before you learn to handle exceptions in a program, it's good to see what happens if you don't deal with them. The following applet includes an expression deliberately causing the error to be removed by 0.
1 class Exc0 {2 Public Static void Main (String args[]) {3 int d = 0; 4 int a = n/ D; 5 }6 }
When the Java runtime system checks for a condition that is removed by 0, it constructs a new exception object and then throws the exception. This causes the execution of the Exc0 to stop, because once an exception is thrown, it must be caught by an exception handler and processed immediately. In this example, we do not provide any of our own exception handlers, so exceptions are caught by the Java runtime system's default handler. Any exception that is not caught by your program will eventually be processed by the default handler. The default handler displays a string that describes the exception, prints the stack track where the exception occurred, and terminates the program.
The following is the output produced by the standard JAVAJDK runtime interpreter executing the program:
1 Java.lang.ArithmeticException:/by Zero2at exc0.main (exc0.java:4)
Note that the class name Exc0, the method name main, the file name Exc0.java, and the number of rows 4 are included in a simple stack usage trajectory. Also, note that the exception type thrown is a subclass of exception named ArithmeticException that more specifically describes what type of error method. As discussed later in this chapter, Java provides several built-in exception types that match the different kinds of run-time errors that may arise.
The stack trace shows the sequence of method calls that caused the error. For example, here is another version of the previous program that describes the same error, but the error is generated in another method other than the main () method:
1 classExc1 {2 Static voidsubroutine () {3 intd = 0;4 intA = 10/D;5 }6 Public Static voidMain (String args[]) {7 exc1.subroutine ();8 }9}
The stack trace result of the default exception handler shows how the entire call stack is displayed:
1 Java.lang.ArithmeticException:/by Zero2at exc1.subroutine (exc1.java:4) 3 At Exc1.main (exc1.java:7)
As you can see, the bottom of the stack is the 7th line of Main, which calls the subroutine () method. This method causes an exception in line 4th. The call stack is important for debugging because it identifies the exact steps that lead to the error.
Series Articles:
Java know how much (top)
Java know how much (interface) interface
Java knows how much (40) the difference between an interface and an abstract class
Java know how much (41) generic explanation
Java know how much (42) the range of generic wildcard characters and type parameters
Java know how much (43) Exception Handling Basics
Java know how much (44) exception type
Java know how much (45) uncaught exceptions