0

当我们可以在单个默认异常中处理它时,为什么我们应该使用多个捕获?

public static void main(String[] args) {  

       try{    
            int a[]=new int[5];    
            a[5]=30/0;    
           }    
           catch(ArithmeticException e)  
              {  
               System.out.println("Arithmetic Exception occurs");  
              }    
           catch(ArrayIndexOutOfBoundsException e)  
              {  
               System.out.println("ArrayIndexOutOfBounds Exception occurs");  
              }    
           catch(Exception e)  
              {  
               System.out.println("Parent Exception occurs");  
              }             
           System.out.println("rest of the code");    
}  
4

3 回答 3

1

如果您使用特定的异常,比如说 SqlException,它会处理所有可能的异常代码,但在 if-else 阶梯中,您需要定义所有可能的场景,您很可能会错过其中的一些。

于 2020-01-12T09:52:13.720 回答
0

请从下次开始正确格式化您的问题。尝试添加您尝试解决问题的内容并尽可能多地解释您的方法。

谈到实际的答案,您使用多个异常来为每种类型的异常提供特定的处理机制。

例如,如果您想单独处理 DivideByZero 异常,例如向用户显示特定消息,您可以通过捕获 DivideByZero Exception 来实现,因为您无法使用通用异常执行相同的操作。

于 2020-01-11T22:38:13.300 回答
0

除此之外,通用异常可以处理所有异常,但随后消息变得通用。在这里,我们需要特定于每种异常类型的消息。

于 2020-01-11T22:43:16.590 回答