Arithmetic overflow exception and checked block in C#

Arithmetic overflow exception and checked block in C#

In this article, we are going to explore How computers do the arithmetic operation perform in computer and how languages like C# and C++ will handle it.

In C# if the Arithmetic overflow happens compiler doesn’t give any exception. It just gives garbage value.

Try with the example in C#

uint a= 4000000000;
uint b= 4000000000;
uint z = a + b;
Console.WriteLine(z);

OP>3705032704 —->(wrong output)

Let’s take an example of unsigned char which stores 8-bit data. (I am taking an example of C++ for simplicity concept will be applied for both C++ and C#) 8 bit can store the 1 to 255 different values. so what happens if I will add 1 to 255. the output will be 0.

Welcome to the world of overflow.

When we do the arithmetic operation on the paper we have as much space as can write to 256. But there is a difference in the case of the computer world as we know everything is converted into the binary form. Suppose we want to do the same operation in binary 8 bit 255 -> 1111 1111

  • 1 => 0000 0001

Result=>1 0000 0000

Notice that result require 9 bit to hold it But unsigned char can hold only 8 bits of data so it simply extra lost the extra bit. And answer we got 0 which is absolutely wrong. In both languages, we don’t get any errors. Actually, in processors, there is a special register known as the CPU status register. In this register, there is one bit called carry flag which is get set when an overflow happens. Here the Checked(c#) block comes into the picture. The checked {} block will check the flag register after each arithmetic operation where the carry flag is set if set then raise the exception.

Why C# don’t do implicit checking of the flag register?

Answer is here

Sometimes we don’t need to check the overflow and in some programs, we have tones of arithmetic operations performed and as per the theory for each operation compiler goes to check the status register which leads to a heavy performance penalty.

So this may be the reason the C# compiler doesn’t provide implicit overflow checking. rather it gives us to do whenever we require using checked block

using checked block

uint a= 4000000000;

uint b = 4000000000;

checked
{
      uint z = a + b;
      Console.WriteLine(z);
}

OP> Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow. Note => VB checks the flag register after each arithmetic operation.

I hope you learn something new :). thanks for reading Keep learning .....