Catch System.OverflowException caused by a numeric overflow

Date Added: July 28, 2010 21:05 by By Edward
Categories: ASP.NET

As a .NET developer, you can sometimes spend hours finding errors and handling them when you do not know the core logic of the system, and decent good documentation is not that easy to come by. There are several ways to address erros, by using exceptions. Exceptions are designed to handle errors and most commonly in a "try/catch" statement.

It is good practice to not catch the generic errors, and try and debug from there. If you do this, you are unsure what your code is actually doing - which can result in the business living with the concequences. The key is to know which errors you might expect and catch those and handle them accordingly. An exception I found to be hard to track, is the "OverflowException" exception.

From MSDN: An OverflowException exception is thrown when a casting, conversion or arithmetic operation in a checked context results in an overflow. An overflow occurs when an operation produces a value too large for the destination type, infinity, or Not a Number (NaN).

For example, mathematical operations can cause these type of exceptions. A way to check for this error is to use the 'checked' keyword. The 'checked' keyword is used to detect overflow conditions. You should note that an 'OverflowException' exception occurs only in a checked context.

Here is a code example on how to check for this type of exception, and how to handle it.   

 public static void Main()
    {
        try
        {
            checked
            {
                int aInt;
                int bInt;
                int Sum;

                aInt = 2000000000;
                bInt = 2000000000;
                Sum = aInt + bInt;
            }
        }
        catch (OverflowException oExcep)
        {
            Console.WriteLine("A mathematical operation caused an overflow.");
            // Good idea to log this error and deal with it when doing debugging
            // I am using my own Logging module.
            Logger.LogException(oExcep, "A mathematical operation caused an overflow.");
        }
    }
Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net