...
Code Block | ||
---|---|---|
| ||
public int do_operation(int a,int b) { int temp = a + b; //Could result in overflow //perform other processing return temp; } |
...
Code Block | ||
---|---|---|
| ||
public int do_operation(int a,int b) { int temp = a + b; //Could result in overflow //do other processing return temp; } |
...
Code Block | ||
---|---|---|
| ||
public boolboolean 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(longtemp < Integer.MIN_VALUE || longtemp > Integer.MAX_VALUE) throw ArithmeticException; else result = (int) temp; |
...
Code Block | ||
---|---|---|
| ||
public boolboolean underflow(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.subtract(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 underflow //Can proceed return false; } public int do_operation(int a, int b) throws ArithmeticException { if(undeflow(a,b)) throw ArithmeticException; else //we are within range safely perform the addition } |
...
Code Block | ||
---|---|---|
| ||
if(a == Integer.MIN_VALUE && b == -1)
throw ArithmeticException;//May be Integer.MIN_VALUE again????
else
result = a/b;//safe operation
|
...