Exceptions - checked and unchecked


Overflow may occur in arithmetic expressions and there exists features of the language that relate to these errors. An example of overflow is shown below.

// Exception16 - Arithmetic Overflow

using System;

class Program
{
    static void Main()
    {
        byte a = 255;
        byte b = 1;
        byte c = (byte)(a + b);
        Console.WriteLine("Byte c = {0}", c);
    }
}

The output is shown below.

Byte c = 0

From the result it is clear that arithmetic overflow has occurred. The keyword checked may be used to detect arithmetic overflows via exceptions. The syntax of using checked is shown below.

checked (expression)

checked
 {
  // statements to be checked
 }

In the first form, expression is the expression being checked. In either case, if an expression fails a check the exception OverflowException is thrown. For example the previous program may be rewritten as follows.

// Exception17 - Using Checked

using System;

class Program
{
    static void Main()
    {
        try
        {
            checked
            {
                byte a = 255;
                byte b = 1;
                byte c = (byte)(a + b);
                Console.WriteLine("Byte c = {0}", c);
            }
        }
        catch (OverflowException)
        {
            Console.WriteLine("An arithmetic overflow occurred");
        }
    }
}

The program prints out the following.

An arithmetic overflow occurred

There is also an unchecked keyword with a similar syntax to checked. Clearly, unchecked is the default. The next program delivers default behaviour.

// Exception18 - Using unchecked

using System;

class Program
{
    static void Main()
    {
        try
        {
            unchecked
            {
                byte a = 255;
                byte b = 1;
                byte c = (byte)(a + b);
                Console.WriteLine("Byte c = {0}", c);
            }
        }
        catch (OverflowException)
        {
            Console.WriteLine("An arithmetic overflow occurred");
        }
    }
}

The printout of this program is now.

Byte c = 0