如何在Java中处理ArithmeticException(未检查异常)?


java.lang.ArithmeticException是Java中的一个未检查异常。通常,你会遇到java.lang.ArithmeticException: / by zero,这发生在尝试除以两个数字,而分母为零时。ArithmeticException对象可能由JVM构造。

示例1

在线演示

public class ArithmeticExceptionTest {
   public static void main(String[] args) {
      int a = 0, b = 10;
      int c = b/a;
      System.out.println("Value of c is : "+ c);
   }
}

在上例中,由于分母值为零,发生了ArithmeticException

  • java.lang.ArithmeticException:Java在除法过程中抛出的异常。
  • / by zero:是在创建ArithmeticException对象时,给ArithmeticException类提供的详细信息。

输出

Exception in thread "main" java.lang.ArithmeticException: / by zero
      at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5)


如何处理ArithmeticException

让我们使用try和catch块来处理ArithmeticException

  • try和catch块包围可能抛出ArithmeticException的语句。
  • 我们可以捕获ArithmeticException
  • 对我们的程序采取必要的措施,这样执行就不会中止

示例2

在线演示

public class ArithmeticExceptionTest {
   public static void main(String[] args) {
      int a = 0, b = 10 ;
      int c = 0;
      try {
         c = b/a;
      } catch (ArithmeticException e) {
         e.printStackTrace();
         System.out.println("We are just printing the stack trace.\n"+ "ArithmeticException is handled. But take care of the variable \"c\"");
      }
      System.out.println("Value of c :"+ c);
   }
}

当发生异常时,执行从异常发生点转移到catch块。它执行catch块中的语句,然后继续执行try和catch块之后存在的语句。

输出

We are just printing the stack trace.
ArithmeticException is handled. But take care of the variable "c"
Value of c is : 0
java.lang.ArithmeticException: / by zero
        at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)

更新于:2019年7月30日

6000+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.