เมื่อกำหนดค่าให้ตัวแปร น้อยกว่าค่าต่ำสุดที่รองรับ จะเกิด Underflow JVM ไม่โยน Exception เป็นหน้าที่ของโปรแกรมเมอร์จัดการเอง
ตัวอย่าง: ตรวจสอบ Underflow แบบ Manual
public class UnderflowTest {
public static void main(String[] args) {
int num1 = -2147483648; // Integer.MIN_VALUE
int num2 = -1;
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
long sum = (long) num1 + (long) num2; // คำนวณใน long กัน overflow ชั่วคราว
if (sum < Integer.MIN_VALUE) {
throw new ArithmeticException("Underflow occurred!");
}
System.out.println("Sum: " + (int) sum);
}
}
ผลลัพธ์
Number 1: -2147483648
Number 2: -1
Exception in thread "main" java.lang.ArithmeticException: Underflow occurred!
at UnderflowTest.main(UnderflowTest.java:9)
เทคนิค: แปลงเป็น long (หรือ BigInteger) คำนวณก่อน แล้วเช็คก่อนแปลงกลับ เป็น int/double สำหรับ float/double ใช้ Math.addExact() (Java 8+) ซึ่งโยน ArithmeticException อัตโนมัติ