Try語句可以被嵌套。也就是說,一個try語句可以在另一個try塊內部。每次進入try語句,異常的前后關系都會被推入堆棧。如果一個內部的try語句不含特殊異常的catch處理程序,堆棧將彈出,下一個try語句的catch處理程序將檢查是否與之匹配。這個過程將繼續直到一個catch語句匹配成功,或者是直到所有的嵌套try語句被檢查耗盡。如果沒有catch語句匹配,Java的運行時系統將處理這個異常。下面是運用嵌套try語句的一個例子:
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,the following statement will generate a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + 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
/* If two command-line args are used,then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
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);
}
}
}
如你所見,該程序在一個try塊中嵌套了另一個try塊。程序工作如下:當你在沒有命令行參數的情況下執行該程序,外面的try塊將產生一個被零除的異常。程序在有一個命令行參數條件下執行,由嵌套的try塊產生一個被零除的錯誤。因為內部的塊不匹配這個異常,它將把異常傳給外部的try塊,在那里異常被處理。如果你在具有兩個命令行參數的條件下執行該程序,由內部try塊產生一個數組邊界異常。下面的結果闡述了每一種情況:
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
當有方法調用時,try語句的嵌套可以很隱蔽的發生。例如,你可以把對方法的調用放在一個try塊中。在該方法內部,有另一個try語句。這種情況下,方法內部的try仍然是嵌套在外部調用該方法的try塊中的。下面是前面例子的修改,嵌套的try塊移到了方法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
/* If two command-line args are used,then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception http://www.lxinyul.cc/
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,the following statement will generate a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
該程序的輸出與前面的例子相同。