Why do integer datatypes overflow silently rather than throwing exception

…衆ロ難τιáo~ 提交于 2019-11-26 21:51:15

问题


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?


回答1:


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.




回答2:


The reason is "because the Java Language Specification says so".

Section 4.2.2. Integer Operations of the JLS says:

The integer operators do not indicate overflow or underflow in any way.

To me this makes sense, otherwise you’d need either:

  • an 'NumericOverflowException' to be thrown, which would require a 'try catch', or
  • a flag to be set on the primitive result, which would require a more complex handling of primitive operations

Both of which would make primitives and their operations “not simple”, and simplicity with primitives is a strength not worth sacrificing for a predicable and typically rare occurrence.



来源:https://stackoverflow.com/questions/15998008/why-do-integer-datatypes-overflow-silently-rather-than-throwing-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!