Wednesday, August 24, 2011

Checking Arithmetic Operation Overflow


Arithmetic overflow exception can be checked and prevented for integral type using checked and unchecked operator.

Checked Operator enforce overflow checking when an integral expression exceeds the limitation of that type. By default constant expression generates compile-time errors and non-constant expressions are checked at runtime and throw an error based on compiler option.

public static void Main()
{
             
       int x = int.MaxValue +1; // Compile time error
      
       int a = 123456789;
       int b = 123456789;
      
       int c = a * b; // Throws error based on compiler
                         setting or default settings
      
}

Let’s see, How to use checked operator in this scenario?

public static void Main()
{
      
       int a = 123456789;
       int b = 123456789;
      
       try
       {
              checked {
                           int c = a * b;
                     }
       }
       catch (System.OverflowException ex)
       {
              Console.WriteLine(ex.ToString());
       }
}
Output:








Unchecked Operator –
suppress overflow exceptions while performing arithmetic operations on integral types.

public static void Main()
{
      
int x = unchecked(int.MaxValue +1); // Supresses Overflow
                                   Exception @ compile-time
      
       int a = 123456789;
       int b = 123456789;
      
      
       unchecked
{
              int c = a * b; // Supresses Overflow Exception @ run-time
       }
      
}

If checked or unchecked both operator not specified on arithmetic operation then default setting of compiler will be applied and depend on that it throws an error message on overflow. 


See also
How to use keyword as an Identifier (variable)

1 comment:

  1. it was the good example of arithmetic overflow great sharing here.
    What is Calculus

    ReplyDelete