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
Underflow happens when we try to pop an item from an empty stack. Overflow happens when we try to push more items on a stack than it can hold. An error is a mistake that is probably unrecoverable. An exception is an error that can often be handled, so the program can recover.
Detecting Overflow and Underflow We can detect overflow and underflow by checking, if b >= 0 , that a > MAX - b , otherwise with b < 0 , that a < MIN - b . The reason this works is that, if b is greater than or equal to 0, we can safely subtract it from MAX (if it were negative, subtracting it would cause an overflow).
An OverflowException is thrown at run time under the following conditions: An arithmetic operation produces a result that is outside the range of the data type returned by the operation.
Overflow and underflow are both errors resulting from a shortage of space. On the most basic level, they manifest in data types like integers and floating points. Unlike the physical world, the number stored in a computer exists in a discrete number of digits.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With