How to catch OverflowExceptions

Posted by Vinicius de Melo Rocha on August 28th, 2019


The OverflowException is thrown in .NET when an arithmetic operation or casting, inside a checked context, results in a type overflow.

In Visual Basic .NET, the checked context is on by default, but not in C#.

For example, the following code will not throw an OverflowException:

class Program
{
  static void Main(string[] args)
  {
    long longValue = long.MaxValue;
    System.Console.WriteLine((byte)longValue);
  }
}

// Output: 255

To correctly check for OverflowExceptions in C#, you have to wrap the code inside a check block.

class Program
{
  static void Main(string[] args)
  {
    long longValue = long.MaxValue;
    try
    {
      checked
      {
        System.Console.WriteLine((byte)longValue);
      }
    }
    catch (System.OverflowException)
    {
      System.Console.WriteLine($"Unable to cast {longValue} to byte.");
    }
  }
}

// Output: Unable to cast 9223372036854775807 to byte.

For more information on OverflowException, check the official documentation.