如何在 Java 中检查下溢是否发生?
当将一个值分配给一个变量时,该值小于该变量允许的最小值,则发生下溢。如果在 Java 中发生下溢,JVM 不会抛出异常,由程序员负责处理下溢条件。
范例
public class UnderlowTest { public static void main(String[] args) { int num1 = -2147483648; int num2 = -1; System.out.println("Number 1: " + num1); System.out.println("Number 2: " + num2); long sum = (long)num1 + (long)num2; if(sum < Integer.MIN_VALUE) { throw new ArithmeticException("Underflow occurred!"); } System.out.println("The sum of two numbers : " + (int)sum); } }
输出
Number 1: -2147483648 Number 2: -1 Exception in thread "main" java.lang.ArithmeticException: Underflow occurred! at UnderlowTest.main(UnderlowTest.java:9)
广告