C#中算术溢出的防治方法是什么?
并将算术溢出(逻辑错误)转换为运行时错误?
我想至少有3种方法来解决这个问题!
发布于 2014-06-11 05:23:21
你可以用“检查”。
int z = 0;
try
{
// The following line raises an exception because it is checked.
z = checked(maxIntValue + 10);
}
catch (System.OverflowException e)
{
// The following line displays information about the error.
Console.WriteLine("CHECKED and CAUGHT: " + e.ToString());
}
// The value of z is still 0.
return z;参见http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx中的示例和说明
按照任择议定书的要求,采取更多的方法来做到这一点:
您还可以使用Int32.MaxValue (用于int算术)检查某个操作是否会导致溢出,然后抛出您自己的异常或System.OverflowException。
有点像if ((Int32.MaxValue - x) < y) throw new Exception()
https://stackoverflow.com/questions/24155084
复制相似问题