...
Another example would be of explicit range checking would be:
Code Block |
---|
|
public int do_operation(int a, int b) throws ArithmeticException
{
long temp = (long)a+(long)b;
if(a>0 && b>0 && (a >Integer.MAX_VALUE - b) || a<0 && b<0 && (a < Integer.MIN_VALUE -b))
throw ArithmeticException;
else //Value within range can perform the addition
//Do stuff return
(int)temp;
}
|
Another compliant approach would be to use the BigInteger class in this example and in the examples of the other operations using a wrapper for test of the overflow:
Code Block |
---|
|
public bool overflow(int a, int b)
{
java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a));
java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b));
java.math.BigInteger br = ba.add(bb);
if(br.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) == 1
|| br.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE))== -1)
return true;//We have overflow
//Can proceed
return false
}
public int do_operation(int a, int b) throws ArithmeticException
{
if overflow(a,b)
throw ArithmeticException;
else //we are within range safely perform the addition
}
|
...
Code Block |
---|
|
int a,b,result;
long temp = (long) a\* (long)b;
if(temp > Integer.MAX_VALUE \|\| temp < Integer.MIN_VALUE)
throw ArithmeticException;//overflow
else
result = (int) temp;//Value within range, safe to downcast
|
...
Code Block |
---|
|
if(a == Integer.MIN_VALUE && b == \-1)
throw ArithmeticException;//May be Integer.MIN_VALUE again????
else
result = a/b;//safe operation
|
...
Code Block |
---|
|
java.math.BigInteger big_long_max = new java.math.BigInteger(String.valueOf(Long.MAX_VALUE));
System.out.println("big_long="+big_long_max);
big_long_max = big_long_max.add(java.math.BigInteger.valueOf(1));//same as \++big_long_max
System.out.println("big_long="+big_long_max);
These print
big_long=9223372036854775807
big_long=9223372036854775808//exceeds the maximum range of long, no problem\!
java.math.BigInteger big_long_min = new java.math.BigInteger(String.valueOf(Long.MIN_VALUE));
System.out.println("big_long_min="+big_long_min);
big_long_min = big_long_min.subtract(java.math.BigInteger.valueOf(1));//same as \--big_long_min
System.out.println("big_long_min="+big_long_min);//goes bellow minimum range of long, no problem\!
These print:
big_long_min=-9223372036854775808
big_long_min=-9223372036854775809
if(big_long < Long.MAX_VALUE && big_long > Long.MIN_VALUE)//value within range can go to the primitive type
long value = big_log.longValue();//get primitive type
else
//Perform error handling. We can not downcast since the value can not be represented as a long
|
...