我们可以在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 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短