OverflowException
What could provoke an OverflowException
in a C# program? An OverflowException
is only thrown in a checked context.
This exception alerts you to an integer overflow. Overflow is a situation where the number becomes too large to be represented in the bytes.
This program 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
is 4 bytes. More bytes would be needed to represent the desired number.class Program { static void Main() { checked { 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.
The OverflowException
helps us learn of logical errors. With the checked context, we detect these hard-to-find bugs. We improve the logic of our code.