在Java中处理多个catch子句
到目前为止,我们已经了解了如何使用单个catch块,现在我们将看到如何在单个try块中使用多个catch块。
在Java中,当我们在一个try{}块中处理多个异常时,我们可以使用多个catch块来处理运行程序时可能生成的多种异常。但是,每个catch块只能处理一种类型的异常。当try块具有引发不同类型异常的语句时,此机制是必需的。
下面给出了使用多个catch子句的语法:
try{
???
???
}
catch(<exceptionclass_1><obj1>){
//语句
exception
}
catch(<exceptionclass_2><obj2>){
//语句
exception
}
catch(<exceptionclass_N><objN>){
//语句
exception
}引发异常时,将暂停正常执行。运行时系统继续查找可以处理异常的匹配catch块。如果未找到任何处理程序,则该异常由顶级的默认异常处理程序处理。
我们来看下面给出的示例,该示例显示了单个try块的多个catch块的实现。
public class Multi_Catch
{
public static void main(String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;
int res=0;
try
{
res = num1/num2;
System.out.println("The result is" +res);
for(int ct =2;ct >=0; ct--)
{
System.out.println("The value of array are" +array[ct]);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error?. Array is out of Bounds");
}
catch (ArithmeticException e)
{
System.out.println ("Can't be divided by Zero");
}
}
}在此示例中,ArrayIndexOutOfBoundsException和ArithmeticException是我们用来捕获异常的两个catch子句,其中可能导致异常的语句保留在try块中。执行程序时,将引发异常。现在,第一个catch块被跳过,第二个catch块处理该错误。
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便