Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do integer datatypes overflow silently rather than throwing exception

I have learnt(atleast in java) that integer/long values overflow silently and their values start over from minimum value on overflow rather than throwing any exception.

I was using an external api for some file operations, in which max file size was being loaded from a property file. All was fine in my local testing environment. As soon as the code went to live environment, the max file size limit was not working at all. After two days of debugging/analyzing the code, there was no success at all. Then for some other reasons, I took the live constants.properties file and debugged the code with that. o_0

I just want to ask, what prevented them to throw exception on overflow?

like image 580
Syed Aqeel Ashiq Avatar asked Apr 14 '13 10:04

Syed Aqeel Ashiq


People also ask

Why does integer overflow happen?

(Arithmetic) Integer Overflows An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).

What happens if integer overflow in Java?

If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there. If you think that this may occur more than often, then consider using a datatype or object which can store larger values, e.g. long or maybe java. math.

How is integer overflow different from floating point overflow?

"When integer overflow occurs the value of the offending variable will “wrap around” to negative val-ues, producing erroneous results. When floating-point overflow occurs, the value of the offending variable will be set to the constant inf representing infinity."

How can integer overflows be avoided?

Avoidance. By allocating variables with data types that are large enough to contain all values that may possibly be computed and stored in them, it is always possible to avoid overflow.


1 Answers

In many cases Java is based on C or C++ and these are based on Assembly. An overflow/underflow is silent in C and C++ and almost silent in assembly (unless you check special flags). This is likely due to the fact that C and C++ didn't have exceptions when they were first proposed. If you wanted to see overflows/underflows you just used a larger type. e.g. long long int or long double ;) BTW assembly has something similar to exceptions called traps or interrupts, overflows/underflow doesn't cause a trap AFAIK.

What I prefer to do is use long and double unless I am sure these types are much larger than needed. You can't have a device which overflows long in size.

like image 116
Peter Lawrey Avatar answered Oct 17 '22 13:10

Peter Lawrey