我们可以在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