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 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短