I am performing arithmetic operations on integers in a checked scope in C#/.NET, in order to catch when an overflow happens. I want to find out if the overflow was positive or negative, in a short, smart, simple way, without a lot of special cases and checks depending on the operands or operation.
checked
{
try
{
// The code below is an example operation that will throw an
// overflow exception, that I expect to be a positive overflow.
// In my real code, all arithmetic operations are included in this
// code block and can result in both positive and negative overflows.
int foo = int.MaxValue;
int bar = 1;
foo += bar;
}
catch (OverflowException)
{
// I have found out that a overflow occurred,
// but was it positive or negative?
}
}
Can it be done? I found no information in the exception itself to use to find out.