212 Part I: The Java Language
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
As you can see, this program nests onetryblock within another. The program works as
follows. When you execute the program with no command-line arguments, a divide-by-zero
exception is generated by the outertryblock. Execution of the program with one command-line
argument generates a divide-by-zero exception from within the nestedtryblock. Since the
inner block does not catch this exception, it is passed on to the outertryblock, where it is
handled. If you execute the program with two command-line arguments, an array boundary
exception is generated from within the innertryblock. Here are sample runs that illustrate
each case:
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
Nesting oftrystatements can occur in less obvious ways when method calls are involved.
For example, you can enclose a call to a method within atryblock. Inside that method is
anothertrystatement. In this case, thetrywithin the method is still nested inside the outertry
block, which calls the method. Here is the previous program recoded so that the nested
tryblock is moved inside the methodnesttry( ):
/* Try statements can be implicitly nested via
calls to methods. */
class MethNestTry {
static void nesttry(int a) {
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero