Java 异常处理中的嵌套 try 块
java 8object oriented programmingprogramming更新于 2025/11/29 17:16:17
顾名思义,Java 中 try 块内部嵌套 try 块称为嵌套 try 块。当外部和内部等不同的块可能导致不同的错误时,就需要嵌套 try 块。为了处理这些错误,我们需要嵌套的 try 块。
现在让我们看一个实现嵌套 try 块的示例 −
示例
class Main {
// main 方法
public static void main(String args[]) {
try {
int a[]=new int[10];
// 显示索引 12 处的元素
System.out.println(a[12]);
// 另一个 try 块
try {
System.out.println("Division");
int res = 100/ 0;
}
catch (ArithmeticException ex2) {
System.out.println("Sorry! Division by zero isn't feasible!");
}
}
catch (ArrayIndexOutOfBoundsException ex1) {
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}
输出
ArrayIndexOutOfBoundsException
现在我们将对上面的示例进行一些修改 −
示例
class Main {
// main 方法
public static void main(String args[]) {
try {
int a[] = {30, 45, 60, 75, 90, 105, 120, 140, 160, 200};
// 显示索引 8 处的元素
System.out.println("索引 8 处的元素 = "+a[8]);
// 另一个 try 块
try {
System.out.println("Division");
int res = 100/ 0;
}
catch (ArithmeticException ex2) {
System.out.println("Sorry! Division by zero isn't feasible!");
}
}
catch (ArrayIndexOutOfBoundsException ex1) {
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}
输出
Element at index 8 = 160 Division Sorry! Division by zero isn't feasible!

