C# OverflowException

This C# page describes the OverflowException. This exception is thrown in a checked context.

OverflowException. 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.

 

 

Example. 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.

Intint.MaxValue

 

Note: An int is four bytes. More bytes would be needed to represent the desired number.

C# program that causes OverflowException

class Program
{
    static void Main()
    {
	checked
	{
	    int value = int.MaxValue + int.Parse("1");
	}
    }
}

Output

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in
an overflow.

We end up with an OverflowException. This could be trapped in a catch block if you needed to handle the problem at runtime. Using a checked context can help alert you to logic problems in your program faster.

 

Discussion. 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.

 

In the above program, if you use no checked context (or the unchecked context), the program proceeds like nothing is amiss. It doesn't give you the number you probably expect. And this could cause problems you don't expect.

CheckedUnchecked

 

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.