Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีจัดการ ArithmeticException (unchecked) ใน Java

java.lang.ArithmeticException เป็น unchecked exception ใน 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: Exception ที่ Java โยนระหว่างการหาร
  • / by zero: คือข้อความรายละเอียดที่ส่งให้กับคลาส ArithmeticException ขณะสร้างออบเจ็กต์ ArithmeticException

ผลลัพธ์

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

วิธีจัดการ ArithmeticException

มาจัดการ ArithmeticException โดยใช้ try-catch blocks

  • ล้อมรอบคำสั่งที่อาจโยน ArithmeticException ด้วย try-catch blocks
  • จับ 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);
    }
}

เมื่อ exception เกิดขึ้น การทำงานจะกระโดดไปที่ catch block จากจุดที่ exception เกิดขึ้น ทำงานคำสั่งใน catch block แล้วต่อไปทำงานคำสั่งหลัง try-catch blocks

ผลลัพธ์

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)