C# OverflowExceptionUnderstand the OverflowException, which is thrown in a checked context.
What could provoke an OverflowException? An OverflowException is only thrown in a checked context. It alerts you to an integer overflow: a situation where the number becomes too large to be represented in the bytes.Exception
Let's look at this simple program. It declares a checked programming context inside the Main method. Next, we assign an int variable to one greater than the maximum value that can be stored in an int.Int, uintint.MaxValue
Note: An int is 4 bytes. More bytes would be needed to represent the desired number.
Info: If you use no checked context (or the unchecked context), the program proceeds like nothing is amiss.
And: It doesn't give you the number you probably expect. And this could cause problems you don't expect.Checked
C# program that causes OverflowException
static void Main()
int value = int.MaxValue + int.Parse("1");
Unhandled Exception: System.OverflowException:
Arithmetic operation resulted in an overflow.
With the checked context, bugs in our programs that would be silently ignored are changed into serious errors. Control flow is interrupted and programs are terminated. These bugs do not silently slip into the program.
OverflowException: This could be trapped in a catch block if you needed to handle the problem at runtime.
Thus: Using a checked context can help alert you to logic problems in your program faster.
Summary. The OverflowException is a useful way of learning of logical errors in our C# programs. With the checked context, we detect these hard-to-find bugs. We improve the logic of our software in a more systematic way.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.