我们如何在Java中检查下溢?

我们如何在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<strong> </strong>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)

以上就是我们如何在Java中检查下溢?的详细内容,更多请关注其它相关文章!