Java异常处理中的嵌套try块
顾名思义,try块中的try块在Java中称为嵌套try块。当不同的块(例如外部和内部)可能导致不同的错误时,就需要这样做。要处理它们,我们需要嵌套的try块。
现在让我们看一个实现嵌套try块的示例-
示例
class Main {
// main method
public static void main(String args[]) {
try {
int a[]=new int[10];
//显示索引12处的元素
System.out.println(a[12]);
// another try block
try {
System.out.println("相除");
int res = 100/ 0;
}
catch (ArithmeticException ex2) {
System.out.println("抱歉的!。 被零除是不可行的!");
}
}
catch (ArrayIndexOutOfBoundsException ex1) {
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}输出结果
ArrayIndexOutOfBoundsException
现在我们将在上面的示例中进行一些更改-
示例
class Main {
// main method
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]);
// another try block
try {
System.out.println("相除");
int res = 100/ 0;
}
catch (ArithmeticException ex2) {
System.out.println("抱歉的!被零除是不可行的!");
}
}
catch (ArrayIndexOutOfBoundsException ex1) {
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}输出结果
显示索引8处的元素 = 160 Division 抱歉的!被零除是不可行的!
热门推荐
10 结婚对白誓言简短祝福语
11 文艺结婚祝福语短语简短
12 祝球员赛前祝福语简短
13 春节后的祝福语简短
14 订婚新发言简短祝福语
15 简短的祝福语12字
16 虎年开新车祝福语简短
17 友谊晚上祝福语大全简短
18 喜得新房文案祝福语简短