Overflow exception is throwing- even the value exceeds the limit

核能气质少年 提交于 2019-12-10 10:06:59

问题


Why the following code Gives output as -2 instead for throwing overflow exception?

 long x = long.MaxValue;
 long y = long.MaxValue + x;

回答1:


The actual behaviour depends on project settings, unchecked etc. To ensure overflow exception use checked, e.g.

 checked {
   long x = long.MaxValue;
   long y = long.MaxValue + x;
 }



回答2:


Presumably because you're executing it in an unchecked context. Arithmetic on the primitive integer types can execute in a checked or unchecked context. Operations which overflow throw an exception in a checked context, and just use the bottom N bits (depending on the type) in an unchecked context. The default depends on the project settings, but the "default default" is unchecked.

You can either explicitly perform the operation in a checked context, or change the project settings.

Doing it explicitly (just for the arithmetic):

long x = long.MaxValue;
long y = checked(long.MaxValue + x);

Note that constant expressions are checked at compile time, and overflow will result in a compile-time error unless it's explicitly unchecked (regardless of project settings). For example:

long x = long.MaxValue + 1; // Error
long y = unchecked(long.MaxValue + 1); // Equivalent to y = long.MinValue


来源:https://stackoverflow.com/questions/32201811/overflow-exception-is-throwing-even-the-value-exceeds-the-limit

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