Overflow Exception

Overflow is where you try to fit a bigger number than the variable type can hold. There’s two types of errors relating to this issue. The first is a complier time error. This is where you on purpose try to assign a larger number than it can hold. For example:

{ 
   byte a = 256; 
}

The above will cause Visual Studio to inform you that the constant value cannot be converted to type byte. This is the same if the number is too small to fit as well.

Cannot convert to byte

There is also a runtime exception called OverflowException and by default this exception is disabled, but can be enabled using the ‘checked’ keyword.

This exception only occurs when a arithmetic operations happens and when enclosed with the checked keyword.

For example if you want to add to the max value. Lets see what the output produces:

{ 
   byte a = byte.MaxValue; 
   a++; 
   Console.WriteLine(a.ToString());
 
   byte b = byte.MaxValue; 
   b = (byte)(b + 10); 
   Console.WriteLine(b.ToString());
 
   sbyte c = sbyte.MaxValue; 
   c++; 
   Console.WriteLine(c.ToString());
 
   sbyte d = sbyte.MaxValue; 
   d = (sbyte)(d + 10); 
   Console.WriteLine(d.ToString()); 
}

When adding to MaxValue  the next numbers start again from the MinValue, as you can see from the result:

byte add to max value - overflow

The same occurs if you want to subtract from the MinValue, the next value will be the variables MaxValue.

In the above example I have used the type byte but this is also valid for other number types like Int, Short and Long.

Exception Checking

Because overflow is disabled by default as stated above, to check for overflow you must use the ‘checked’ keyword. By doing so when overflow occurs, an exception will be thrown and not just ignored.

try 
{ 
   checked 
   { 
      byte a = byte.MaxValue; 
      a++; 
   } 
} 
catch (OverflowException ex) 
{ 
   // Overflow exception caught, code to handle exception goes here 
}