我们可以在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
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短