As a C# programmer you always should be always aware of right output of arithmetic operation. Your code might be right, there is no runtime exception still your output may be wrong and it may cause important problem in your project. To understand this theory, see below programming example first.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Checked_Unchecked
{
    class Program
    {
        static void Main(string[] args)
        {
            sbyte n1 = 20, n2 = 30, result;
            result = (sbyte)(n1 * n2);
            Console.WriteLine("{0} x {1} = {2}", n1, n2, result);
            Console.ReadKey();               
        }
    }
}

Explanation

In above example, we have used sbyte variable for simple arithmetic calculation. The multiply of n1 and n2 should be 600 but you will get output 88. It will not through any exception and error still your program is right. It is done because you have used small variable without using checked and unchecked statement. The size of sbyte is -128 to 127 only; so the result is overflowed.

How to handle overflow exception using checked and unchecked statement?

It very easy to fix this problem using checked and unchecked statement.Checked strictly monitor your code and if any overflow exception generated it sends control to catch for handling exception. Unchecked statement ignores overflow exception and shows output.

To understand it, see the below programming example of checked and unchecked statements.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Checked_Unchecked
{
    class Program
    {
        static void Main(string[] args)
        {
            sbyte n1 = 20, n2 = 30, result;
            try
            {
                unchecked
                {
                    result = (sbyte)(n1 * n2);
                    Console.WriteLine("{0} x {1} = {2}", n1, n2, result);
                }
                checked
                {
                    result = (sbyte)(n1 * n2);
                    Console.WriteLine("{0} x {1} = {2}", n1, n2, result);
                }
            }
            catch (OverflowException oex)
            {
                Console.WriteLine(oex.Message);
            }
            Console.ReadKey();
        }
    }
}

Explanation

In above example, we have the same program as above but in the checked and unchecked block with exception handling. You will see two outputs; first one is unchecked output that is 88 and second one is overflow exception message.

Leave a Reply

Your email address will not be published. Required fields are marked *