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 one try block 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 outer try block. Execution of the program with one command-line
argument generates a divide-by-zero exception from within the nested try block. Since the
inner block does not catch this exception, it is passed on to the outer try block, where it is
handled. If you execute the program with two command-line arguments, an array boundary
exception is generated from within the inner try block. 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 of try statements can occur in less obvious ways when method calls are involved.
For example, you can enclose a call to a method within a try block. Inside that method is
another try statement. In this case, the try within the method is still nested inside the outer try
block, which calls the method. Here is the previous program recoded so that the nested
try block is moved inside the method nesttry( ):
/* 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
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home