I have two test methods. The first one works fine. The second one does not throw an exception, but it should. Why doesn't the second one throw a exception?
[TestMethod]
[ExpectedException(typeof(OverflowException))]
public void LongToInt_OverflowWithCheckedBlock()
{
checked
{
int maxValue = 2147483647;
long longValue = (maxValue + 1);
int intValue = (int)longValue;
}
}
[TestMethod]
[ExpectedException(typeof(OverflowException))]
public void LongToInt_OverflowWithCheckedStatement()
{
int maxValue = 2147483647;
long longValue = (maxValue + 1);
int intValue = checked((int)longValue); // No Exception is thrown, why?
}
longValue = maxValue + 1
does the arithmetic in 32 bit integers first and then converts to 64 bit. The most common form of this bug isdouble percent = someInteger / 100;
, and the question is then "why is my percentage always zero?" You have to convert to the type you intend to do the arithmetic in before you do the arithmetic, not after.