到目前为止,我们已经了解了如何使用单个catch块,现在我们将看到如何在单个try块中使用多个catch块。
在Java中,当我们在一个try {}块中处理多个异常时,我们可以使用多个catch块来处理运行程序时可能生成的多种异常。但是,每个catch块只能处理一种类型的异常。当try块具有引发不同类型异常的语句时,此机制是必需的。
下面给出了使用多个catch子句的语法:try{
???
???
}
catch(){
//语句
exception
}
catch(){
//语句
exception
}
catch(){
//语句
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块处理该错误。