Java Reference
In-Depth Information
I want to start with a simple example to demonstrate how an exception affects the
fl ow of control of an application. The following
ExceptionDemo
class generates an
ArithmeticException
on line 15 when
5
is divided by
0
. Study the code and see if you can
determine its output.
1. public class ExceptionDemo {
2. public void method1() {
3. System.out.println(“Inside method1”);
4. method2();
5. }
6.
7. public void method2() {
8. System.out.println(“Inside method2”);
9. method3();
10. }
11.
12. public void method3() {
13. System.out.println(“Inside method3”);
14. int x = 5, y = 0;
15. int z = x/y; //throws an ArithmeticException
16. System.out.println(“z = “ + z);
17. }
18.
19. public static void main(String [] args) {
20. System.out.println(“Inside main”);
21. new ExceptionDemo().method1();
22. System.out.println(“End of main”);
23. }
24.}
Here is the sequence of events that occurs in this program:
1.
Running the program puts the
main
method on the bottom of the call stack. (Figure 3.7
shows the method call stack.)
Inside main
displays on line 19 and
method1
is invoked
on a new
ExceptionDemo
object.
2.
method1
is pushed on the call stack.
Inside method1
displays on line 3 and
method2
is called.
3.
method2
is pushed on the call stack.
Inside method2
displays on line 8 and
method3
is called.
4.
method3
is pushed on the call stack.
Inside method3
displays, and then line 15 causes
an
ArithmeticException
to be thrown.
Search WWH ::
Custom Search