What would be the most appropriate way to detect an arithmetic overflow (or underflow for that matter) and get the overflow count?
For easier understanding I'll will be using byte, but this is the same for int or any other basic integer type. Now imagine I have the value 240 and want to add 24 to it. Clearly an arithmetic overflow. Using the checked keyword this is easy to detect at least ...
byte value = 240;
try
{
checked
{
value += 24;
}
}
catch (OverflowException e)
{
// handle overflow, get overflow count via % etc.
}
... by throwing an exception.
This is what I am using at the moment.
However, I don't quite like the exception handling in this one. Exceptions are usually pretty expensive, and I want to avoid them right from the start. To me this seems like a Boneheaded-Exception anyways. Is there some arithmetic wizardry I could do to detect this upfront?