This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hello, Considering that Java does not automatically throw an exception (or otherwise object) to integer overflow (it just "wraps around"), what is the best/preferred/whatever style to handle this condition when it is unknown that the inputs and subsequent calculations will for certain stay within bounds (of Integer.MAX_VALUE and Integer.MIN_VALUE in the case of type int)? Should values first be stored as type long and the appropriate comparisons made before continuing? Then, in the case of using data of type long, is there a better way of handling the situation than first storing the data as BigInteger objects and making the appropriate comparisons? For the purposes of reuse, my thought was to create my own class with static methods that checked the input data and subsequent calculations that the appropriate bounds were not exceeded; but if they were, then trow some custom exception. Or is this function already in one of the standard Java classes? Thanks for the advice.
The built-in integer operators do not indicate overflow or underflow in any way.
From that, I'm left with only trickery to determine when overflow or underflow occured. If your using an int, you can try an approach like this:
This will vaguely work. However, if the overflow were so great that the ensuing wrapping brought the resultant value within the valid range of an int again, the overflow or underflow wouldn't be caught. Of course, this doesn't slove anything for catching overflow or underflow on a long... Sorry, this is the best way I know. Corey
Well, I searched all over the web for articles on this subject, and it would seem that no magic trick is available to deal with a possible integer overflow. Oh well. It looks as if we'll just have to do it the hard way. Nuts to that. Good Luck. [ April 05, 2002: Message edited by: Dirk Schreckmann ]
Here's what I came up with that might be useful for dealing with longs:
Naturally you can add additional methods for subtraction and division, as well as any other operations you want to use. And it may well be possible to improve on the implementations I've provided - I just tossed them off quickly. But I think the basic idea is useful. If you do decide to build something like this, please let us know what you come up with - it may well be useful for others.