C# 中的 int 没有溢出异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2056445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
No overflow exception for int in C#?
提问by erikric
I had this weird experience with problem number 10 on Project Euler(great site by the way). The assignment was to calculate the sum of all the prime numbers below two million.
我在Project Euler(顺便说一下很棒的网站)上遇到了问题 10 的奇怪经历。任务是计算所有低于 200 万的素数的总和。
I used an int for the sum, and my algorith produced an answer, but when i pasted it to verify the answer, it was wrong.
我使用了一个整数作为总和,我的算法产生了一个答案,但是当我粘贴它来验证答案时,它是错误的。
It turned out that the result was too big to fit in an int, but wouldn't this cause an overflow error or something? Instead, it just returned a value far off from the real answer.
结果是结果太大而无法放入一个int,但这不会导致溢出错误或什么的吗?相反,它只是返回一个与真实答案相去甚远的值。
When I changed the type to long, everything was hunky dory.
当我将类型更改为 long 时,一切都是笨拙的。
采纳答案by Konrad Rudolph
C# integer operations don't throw exceptions upon overflow by default. You can achieve that via the project settings, or by making the calculation checked
:
默认情况下,C# 整数运算不会在溢出时引发异常。您可以通过项目设置或进行计算来实现checked
:
int result = checked(largeInt + otherLargeInt);
Now the operation will throw.
现在操作将抛出。
The opposite is unchecked
, which makes any operation explicitly unchecked. Obviously, this only makes sense when you've got checked operations enabled in the project settings.
相反的是unchecked
,它使任何操作都明确取消检查。显然,这仅在您在项目设置中启用检查操作时才有意义。
回答by Dirk Vollmar
In C# an OverflowException
is not thrown (in VB the exception is thrown per default).
在 C#OverflowException
中不抛出(在 VB 中默认抛出异常)。
To get the excpetion you have to embed your code in a checked
context:
要获得例外,您必须将代码嵌入到checked
上下文中:
byte value = 241;
checked
{
try
{
sbyte newValue = (sbyte) value;
Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
value.GetType().Name, value,
newValue.GetType().Name, newValue);
}
catch (OverflowException)
{
Console.WriteLine("Exception: {0} > {1}.", value, SByte.MaxValue);
}
}
MSDN explains in more detail:
MSDN 有更详细的解释:
For the arithmetic, casting, or conversion operation to throw an OverflowException, the operation must occur in a checked context. By default, arithmetic operations and overflows in Visual Basic are checked; in C#, they are not. If the operation occurs in an unchecked context, the result is truncated by discarding any high-order bits that do not fit into the destination type.
对于抛出 OverflowException 的算术、强制转换或转换操作,该操作必须发生在已检查的上下文中。默认情况下,会检查 Visual Basic 中的算术运算和溢出;在 C# 中,它们不是。如果操作发生在未经检查的上下文中,则会通过丢弃任何不适合目标类型的高位来截断结果。
回答by Andreas Niedermair
i've already added a cmt, but it's maybe interesting for some of you:
我已经添加了一个 cmt,但对你们中的一些人来说可能很有趣:
msdntells us:
msdn告诉我们:
Integer arithmetic overflow either throws an OverflowException or discards the most significant bits of the result
整数算术溢出抛出一个 OverflowException 或丢弃结果的最高有效位
but
但
Decimal arithmetic overflow always throws an OverflowException.
十进制算术溢出总是抛出一个溢出异常。
also
还
When integer overflow occurs, what happens depends on the execution context, which can be checked or unchecked. In a checked context, an OverflowException is thrown. In an unchecked context, the most significant bits of the result are discarded and execution continues. Thus, C# gives you the choice of handling or ignoring overflow.
当整数溢出发生时,会发生什么取决于执行上下文,可以检查或取消检查。在已检查的上下文中,会引发 OverflowException。在未经检查的上下文中,结果的最高有效位被丢弃并继续执行。因此,C# 为您提供了处理或忽略溢出的选择。
回答by Thorarin
By default, C# does not check for arithmetic overflow on integers. You can change this with the /checked
compiler optionor by enabling "Check for arithmetic overflow/underflow" in Visual Studio (project properties - Build - Advanced).
默认情况下,C# 不检查整数的算术溢出。您可以使用/checked
编译器选项或通过在 Visual Studio(项目属性 - 构建 - 高级)中启用“检查算术溢出/下溢”来更改此设置。
You can use checked
and unchecked
keywordsto override the default on a case-by-case basis. If you rely on checking taking place in a piece of code, explicitly enabling it using checked
would be a good idea.
您可以根据具体情况使用checked
和unchecked
关键字来覆盖默认值。如果您依赖于在一段代码中进行的检查,显式启用它使用checked
将是一个好主意。
int j = checked(i * 2);
checked
{
int j = i * 2;
// Do more stuff
}
Note that floating point operations never throw an OverflowException
, and decimal operations always throw an OverflowException
. See also C# operators.
请注意,浮点运算永远不会抛出 an OverflowException
,而十进制运算总是抛出 an OverflowException
。另请参见C# 运算符。
回答by oshan2csd
It's because, by default C# do not throw any exception for integer overflow as well as underflow. There are couple of things you can do here.
这是因为,默认情况下,C# 不会为整数溢出和下溢抛出任何异常。您可以在这里做几件事。
Option 1
选项1
You have to enable the exception to be thrown by go to Project => properties => Build tab => Advanced => check for arithmetic overflow underflow.(make sure you tick the option)
您必须通过转到项目 => 属性 => 构建选项卡 => 高级 => 检查算术溢出下溢来启用要抛出的异常。(确保勾选该选项)
Make sure you tick the option
确保勾选选项
Option 2
选项 2
Use a checked block and throw an overflow exception to handle the situation. A sample code snippet would be
使用检查块并抛出溢出异常来处理这种情况。示例代码片段将是
try
{
checked
{
int y = 1000000000;
short x = (short)y;
}
}
catch (OverflowException ex)
{
MessageBox.Show("Overflow");
}
catch (Exception ex)
{
MessageBox.Show("Error");
}
Hope this will help you... :)
希望能帮到你... :)