为什么我们需要这些“显式”捕获块?

时间:2019-01-11 18:30:33

标签: java exception exception-handling

我正在使用beginnersbook.com上的教程来学习Java中的异常处理。

this code here:

的用途是什么?
class Example1 {
   public static void main(String args[]) {
      int num1, num2;
      try {
         /* We suspect that this block of statement can throw 
          * exception so we handled it by placing these statements
          * inside try and handled the exception in catch block
          */
         num1 = 0;
         num2 = 62 / num1;
         System.out.println(num2);
         System.out.println("Hey I'm at the end of try block");
      }
      catch (ArithmeticException e) { 
         /* This block will only execute if any Arithmetic exception 
          * occurs in try block
          */
         System.out.println("You should not divide a number by zero");
      }
      catch (Exception e) {
         /* This is a generic Exception handler which means it can handle
          * all the exceptions. This will execute if the exception is not
          * handled by previous catch blocks.
          */
         System.out.println("Exception occurred");
      }
      System.out.println("I'm out of try-catch block in Java.");
   }
}

此位:

catch (ArithmeticException e) { 
             /* This block will only execute if any Arithmetic exception 
              * occurs in try block
              */
             System.out.println("You should not divide a number by zero");
          }

当catch(Exception e){...}能够处理所有事情时,为什么我们需要这样做?

我能想到的唯一原因是显示您想要/希望显示的消息,因为您不喜欢e.getmessage()给出的消息。

2 个答案:

答案 0 :(得分:1)

catch语法允许为更具体的异常引入更具体的错误处理。这是一种不错的语法,因为使用Exception的catch非常通用,因此如果不存在此if (ex instanceof ArithmeticException)语法,则必须使用catch

一个例子可能是网络错误处理。如果您的客户端代码声明了RetryableException extends NetworkException,则在捕获RetryableException时可能要重试客户端操作,但不要重试其他任何NetworkException

根据official The catch Blocks docs

  

异常处理程序可以做的不仅仅是打印错误消息或暂停程序。他们可以使用链式异常进行错误恢复,提示用户做出决定或将错误传播到更高级别的处理程序,如“链式异常”部分所述。

答案 1 :(得分:0)

就异常处理而言,就良好的编码习惯而言,对于运行时可能发生或可能不会发生的潜在异常,我们应始终首先捕获最接近/最相关的检查异常。 例如对于文件操作,我们将始终使用 FileNotFoundException

第二个catch块可用于可能发生或可能不发生的异常(在执行第一个易受攻击的语句之后)。

以防万一,我们不确定运行时可能发生的异常类型,因此可以在catch块中使用通用 Exception

在您的示例中,我想作者想传达两种异常处理功能:

  1. 我们可以尝试使用两个catch块。
  2. 您抓到的顺序 例外。首先应该是孩子,然后是父母。 例如。
      

    您正在与您的朋友争论,并且可以在您的控制下解决它,因此很明显,您将自己解决该问题,而不是去找父母,让他们为您解决。

相关问题