Vinicius Rocha

How to catch an OverflowException

Introduction

It is important to understand what happens when we cast numeric values in .NET, the result might not be what you are expecting. Here, I am showing how to use OverflowException to prevent unexpected behaviors.

The Default Behavior

When writing code in C#, if we cast a numeric value to another type that doesn't not have enough bits to represent it, the compiler will truncate the number to the maximum value supported.

For example:

using System;

long longValue = long.MaxValue;
Console.WriteLine((byte)longValue);

// Output: 255

Validate using OverFlowExceptions

In order to ensure that the cast will not silently change the value, we need to wrap the code into a check block.

using System;

long longValue = long.MaxValue;
try
{
  checked
  {
    Console.WriteLine((byte)longValue);
  }
}
catch (OverflowException)
{
  Console.WriteLine($"Unable to cast {longValue} to byte.");
}

// Output: Unable to cast 9223372036854775807 to byte.

Wrapping the code inside a check block will ensure that it will throw an exception if the value is too big for the target type. For more information, check out the official documentation.

Originally posted on dev.to.