Home
C#
OverflowException
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 25, 2021 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.