Reputation: 4574
I am trying to get a hold of overflow and underflow exceptions in java, but couldn't get any nice tutorial. Specifically I wish to learn
Any link to useful tutorial will do
Upvotes: 13
Views: 39927
Reputation: 1785
Since this is a very old question, it should be noted that since Java 8, the Math package provides "exact" arithmetic methods which will trigger exceptions when overflow occurs.
e.g.
int iv1 = Integer.MAX_VALUE;
int iv2 = Math.addExact(iv1,1);
will trigger java.lang.ArithmeticException: integer overflow .
Upvotes: 1
Reputation: 12342
In Java arithmetic, overflow or underflow will never throw an Exception. Instead, for floating point arithmetic the value is set as Not a number
, 'infinite' or zero.
To test for these you can use the static methods: isNaN or isInfinite using the appropriate wrapper classes. You can handle this as appropriate. Example:
double d1 = 100 / 0.;
if (Double.isNaN(d1)) {
throw new RuntimeException("d1 is not a number");
}
if (Double.isInfinite(d1)) {
throw new RuntimeException("d1 is infinite");
}
For certain operations you can get an ArithmeticException, for example when dividing by zero
in Integer maths.
I just asked a related question about a complete project style way to handle this.
Upvotes: 7
Reputation: 23856
Java has no unsigned integers. This makes it easy to throw an Exception, if you think it might be useful.
public class Counter
{
private int counter = 0;
public int increment ()
{
counter += 1;
if (counter < 0)
throw new RuntimeException ("Counter overflow");
else
return counter;
}
public String toString() { return String.valueOf(counter); }
}
Upvotes: 0
Reputation: 223063
Okay, the OP talked about wanting to know about both stack overflow and arithmetic overflow, as well as their corresponding underflow. Here goes....
int
holds values between -231 and 231-1, inclusive. If your number goes over these limits, an overflow occurs, and the number "wraps around". These do not cause an exception to be generated in Java.StackOverflowError
when that happens.To answer the OP's other question (see comments), when you overstep the boundaries of an array, an IndexOutOfBoundsException
is issued.
Upvotes: 30