Home
C#
OverflowException
Updated Nov 25, 2021
Dot Net Perls
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.
Exception
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
int.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
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.
Thus These bugs do not silently slip into the program. Using a checked context can help alert you to logic problems in your program faster.
Detail This could be trapped in a catch block if you needed to handle the problem at runtime.
catch
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 25, 2021 (rewrite).
Home
Changes
© 2007-2025 Sam Allen