我们可以在Java中定义带有多个catch块的try块吗?
是的,我们可以在Java中定义一个try块和多个catch块。
每次尝试都应该并且必须至少与一个捕获块相关联。
每当在try块中识别到异常对象时,并且如果存在多个catch块,则将根据已定义catch块的顺序为catch块指定优先级。
始终将最高优先级赋予第一个捕获块。如果第一个catch块无法处理所标识的异常对象,则它将考虑下一个catch块。
示例
class TryWithMultipleCatch {
public static void main(String args[]) {
try{
int a[]=new int[5];
a[3]=10/0;
System.out.println("First print statement in try block");
} catch(ArithmeticException e) {
System.out.println("Warning: ArithmeticException");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Warning: ArrayIndexOutOfBoundsException");
} catch(Exception e) {
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block");
}
}输出结果
Warning: ArithmeticException Out of try-catch block
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短