Number overflow exception

Unity does not throw an exception after adding 1 to int.MaxValue in block#1 because of an absence of Checked Statement.

How to throw OverflowException: Arithmetic operation resulted in an overflow without Checked Statement?

Hello,

If you don’t put this operation in a checked block, your integer gets wrapped. This is an absolutely standard behaviour from C#, and does not have anything to do with Unity. When you add 1 to 2147483647, it gets wrapped and it is set to -2147483648. The only “easy” way of checking the overflow of an integer is by using the checked block. See there.

Now, if you want to throw an exception without this, you could use a simple condition. Since an integer that has been wrapped is negative, while you were previously being positive, you can simply check if the new value (after the addition) is smaller than the previous value, like this:

int max = int.MaxValue;
if(max + 1 < max)
{
    throw new ArithmeticException("Overflow");
}

Using checked is “only” 3-5% slower than not doing it (source), so if your point is performance, maybe the condition will cost more performance. You should try, I don’t know.

Regards,

troopy28