Java Reference
In-Depth Information
With an exception heading its way, method1() has three choices:
Catch the exception so that it does not go any further down the call stack.
■■
Catch the exception, then throw it back down the call stack.
■■
Not catch the exception, thereby causing method1() to be popped
off the call stack, with the exception continuing down the call stack
to main().
■■
This flow of control continues down the call stack, no matter how many
methods appear on the call stack. Each method further down the call stack
either catches the exception and stops this process, catches the exception and
throws it again, or simply does nothing and lets the exception fall through to
the next method.
What happens when we reach the bottom of the call stack? Well, if an excep-
tion is thrown to main(), then main() had better catch the exception or the pro-
gram will terminate. When an exception reaches the bottom of a call stack and
no method has stopped it along the way, the JVM will crash and inform you of
the details of the exception.
Let's look at an example of what happens when an exception is ignored all
the way down the call stack. The following CrashDemo program has three
methods: main(), method1(), and method2(). Study the program and try to
determine what happens when it executes. The output is shown in Figure 11.1.
public class CrashDemo
{
public static void main(String [] args)
{
System.out.println(“Inside main...”);
int [] values = {1, 2, 3, 4};
System.out.println(“Invoking method1...”);
method1(values);
System.out.println(“*** Back in main ***”);
}
public static void method1(int [] x)
{
System.out.println(“\nInside method1...”);
method2(x);
System.out.println(“*** Back in method1 ***”);
}
public static void method2(int [] y)
{
System.out.println(“\nInside method2”);
System.out.println(y[5]);
System.out.println(“*** Leaving method2 ***”);
}
}
Search WWH ::




Custom Search