Why doesn't this produce an overflow exception?

有些话、适合烂在心里 提交于 2019-12-04 07:44:22

CLR will not throw the Overflow exception by default. Unless you're using the "checked" keyword.

http://msdn.microsoft.com/en-us/library/74b4xzyw%28v=vs.71%29.aspx

UPD: Actually, I do recommend the "CLR via C#" by Jeffrey Richter - he makes these things so much more transparent. My favorite book about the CLR and C# fundamentals.

"For the arithmetic, casting, or conversion operation to throw an OverflowException, the operation must occur in a checked context."

The OverflowException will be called as soon as you put your code within a checked block.

ulong lSmallValue = 5;
ulong lBigValue = 10;
checked {
try {
    ulong lDifference = lSmallValue - lBigValue;
}
catch (OverflowException) {
    Console.WriteLine("Exception caught");
}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!