public static long safeSubtract ( long val1 , long val2 ) { long diff = val1 - val2 ; // If there is a sign change, but the two values have different signs... if ( ( val1 ^ diff ) < 0 && ( val1 ^ val2 ) < 0 ) { throw new ArithmeticException ( "The calculation caused an overflow: " + val1 + " - " + val2 ) ; } return diff ; }
Subtracts two values throwing an exception if overflow occurs .