How does Java handle integer underflows and overflows and how would you check for it?

前端 未结 12 1385
走了就别回头了
走了就别回头了 2020-11-21 06:40

How does Java handle integer underflows and overflows?

Leading on from that, how would you check/test that this is occurring?

12条回答
  •  -上瘾入骨i
    2020-11-21 07:21

    static final int safeAdd(int left, int right)
                     throws ArithmeticException {
      if (right > 0 ? left > Integer.MAX_VALUE - right
                    : left < Integer.MIN_VALUE - right) {
        throw new ArithmeticException("Integer overflow");
      }
      return left + right;
    }
    
    static final int safeSubtract(int left, int right)
                     throws ArithmeticException {
      if (right > 0 ? left < Integer.MIN_VALUE + right
                    : left > Integer.MAX_VALUE + right) {
        throw new ArithmeticException("Integer overflow");
      }
      return left - right;
    }
    
    static final int safeMultiply(int left, int right)
                     throws ArithmeticException {
      if (right > 0 ? left > Integer.MAX_VALUE/right
                      || left < Integer.MIN_VALUE/right
                    : (right < -1 ? left > Integer.MIN_VALUE/right
                                    || left < Integer.MAX_VALUE/right
                                  : right == -1
                                    && left == Integer.MIN_VALUE) ) {
        throw new ArithmeticException("Integer overflow");
      }
      return left * right;
    }
    
    static final int safeDivide(int left, int right)
                     throws ArithmeticException {
      if ((left == Integer.MIN_VALUE) && (right == -1)) {
        throw new ArithmeticException("Integer overflow");
      }
      return left / right;
    }
    
    static final int safeNegate(int a) throws ArithmeticException {
      if (a == Integer.MIN_VALUE) {
        throw new ArithmeticException("Integer overflow");
      }
      return -a;
    }
    static final int safeAbs(int a) throws ArithmeticException {
      if (a == Integer.MIN_VALUE) {
        throw new ArithmeticException("Integer overflow");
      }
      return Math.abs(a);
    }
    

提交回复
热议问题