如何在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+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告