为什么要在异常中使用多个捕获?

问题描述 投票:0回答:1

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

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");    
}  
exception nullpointerexception try-catch indexoutofboundsexception arithmeticexception
1个回答
0
投票

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

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

例如,如果要单独处理DivideByZero异常,例如向用户显示特定消息,则可以通过捕获DivideByZero异常来完成此操作,因为在这种情况下,您无法使用通用异常执行相同的操作。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.