Writing an API for checked subtraction I have to write an API for checked subtraction where the input minuend can be &lt; 0 but subtrahend can't be &lt; 0. I think I've covered all the cases of underflow and overflow. With given conditions the range of subtrahend is [Long.MIN_VALUE, Long.MAX_VALUE] and of minuend is [0, Long.MAX_VALUE]; with these limits overflow is not possible and underflow can happen if subtrahend > minuend and in that case setting Long.MIN_VALUE as the minimum possible difference seems legit. 

public static long checkedSubtract(final long minuend, final long subtrahend) {
    Preconditions.checkArgument(subtrahend &gt;= 0, "Subtrahend must be &gt;= 0");

    long difference;
    try {
        difference = LongMath.checkedSubtract(minuend, subtrahend);
    } catch (ArithmeticException e) {
        // With the precondition of subtrahend &gt;= 0, this operation can not
        // overflow and if it underflows, return minimum possible difference 
        difference = Long.MIN_VALUE;
    }
    return difference;
}


I'd appreciate it if someone could affirm my logic and/or point out any mistake.
I guess your logic is fine. I just don't like what you do with the variable difference. You could return directly instead and save the variable and two lines.

In case the overflow s probable, you're wasting a lot of time because of the exception. You could do something like

long result = minuend - subtrahend;
return minuend &gt;= 0 | (minuend ^ result) &gt;= 0 ? result : Long.MIN_VALUE;


instead (condition adapted from LongMath.checkedSubtract). You could test it both against your original implementation (e.g. with a few random values) and against some known cases.



As suggested by user1071840, a simpler condition may be used:

return Long.MIN_VALUE + subtrahend &gt; minuend ? minuend - subtrahend : Long.MIN_VALUE;


Actually, rolfl's condition is even simpler.