Why, In Java arithmetic, overflow or underflow will never throw an Exception?

后端 未结 4 1767
刺人心
刺人心 2020-12-01 19:52

During Java Arithmetic operation , JVM do not throw Underflow or Overflow Exception. So many time we come across unexpected results and wondering what went wrong.

Wh

4条回答
  •  温柔的废话
    2020-12-01 20:12

    This was likely a combination of factors:

    1. The big languages prior to Java used unchecked arithmetic. Well-known algorithms prone to numerical overflow tended to account for the potential overflow already without relying on checked arithmetic.
    2. Checked arithmetic introduces significant overhead in algorithms making heavy use of arithmetic instructions, which would put Java at a substantial disadvantage especially for benchmarks.
    3. Some algorithms rely on silent numerical overflow/underflow. If arithmetic operations were checked, rewriting these algorithms could quickly become non-trivial.
    4. Checked arithmetic is not necessary to ensure memory safety (as opposed to other JVM checks like null pointers and array bounds).

    The .NET virtual execution environment (now part of the ECMA-335 standard) introduced separate instructions for checked and unchecked arithmetic, allowing it to independently address the performance and safety concerns of developers working in modern managed languages.

提交回复
热议问题