- Home /
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?
Answer by troopy28 · May 26, 2018 at 02:53 PM
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
troopy28 Thank you for clarification. $$anonymous$$aybe do you know about some global option or compiler setting to turn on OverflowException?
I've found one way to set parameter through the compiler. Here.
Controlling Arithmetic Overflow Checking
When compiling a C# program, you can globally turn on arithmetic overflow checking by using the /checked+ command line option, as follows:
c:\ csc /checked+ example.cs
But I don't know how to do it for Unity!
Neither I know... I don't know how to access to the Unity's compiler actually. Nevertheless, if you build your scripts into a DLL, and use that DLL in your Unity project, then you should be able to specify the command line arguments from Visual Studio (which is not possible when using Unity's compiler).