为什么除以int.MinValue -1在unchecked上下文中扔OverflowException异常? [英] Why dividing int.MinValue by -1 threw OverflowException in unchecked context?

查看:210
本文介绍了为什么除以int.MinValue -1在unchecked上下文中扔OverflowException异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int y = -2147483648;
int z = unchecked(y / -1);



第二行导致发生OverflowException 。不应该选中防止这种

例如:

int y = -2147483648;
int z = unchecked(y * 2);



不会导致异常。

doesn't cause an exception.

推荐答案

在C#4规格第7.72(除法运算符)规定:

Section 7.72 (Division Operator) of the C# 4 specs states:

如果左操作数是最小int或long值,右操作数为-1,发生溢出。在checked上下文中,[...]。在unchecked上下文中,是实现定义一个System.ArithmeticException(或其子类)是否被抛出或溢出去与所得到的值是它的左边操作数未报告来。

If the left operand is the smallest representable int or long value and the right operand is –1, an overflow occurs. In a checked context, [...]. In an unchecked context, it is implementation-defined as to whether a System.ArithmeticException (or a subclass thereof) is thrown or the overflow goes unreported with the resulting value being that of the left operand.

所以,这个抛出unchecked上下文中的异常的事实其实也不是一个错误,因为该行为是实现定义的。

So the fact that this throws an exception in an unchecked context is not in fact a bug, since the behavior is implementation-defined.

这篇关于为什么除以int.MinValue -1在unchecked上下文中扔OverflowException异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆