Membership Service in ASP.Net 2.0

Membership Service in ASP.Net 2.0
Published on http://asp.net on 10/16/2008

Tuesday, April 16, 2013

Handling overflow exceptions: Checked/Unchecked


In .Net, when two numbers are added, the corresponding IL code that is generated has two representation and by default .add call is executed.

1. add
2. add.ovf

Because .add is called, the overflows go undetected and might cause the applications built around it to behave erratically. In Order to ensure the overflow check, use of "checked" keyword could be employed

e.g.

Without "checked"


                byte b1 = 100;
                byte b2 = (byte)(b1 + 200);
                Console.WriteLine(b2.ToString());
                Console.ReadKey();

on executing the above piece of the code output would be : 44
Since byte can be b/w 0 and 255. 300-256 =44


       
With "checked"



               byte b1 = 100;
                byte b2 = checked((byte)(b1 + 200));
                Console.WriteLine(b2.ToString());
                Console.ReadKey();

in this case, overflow exception will be thrown.

Similarly, the "unchecked" keyword can be used to perform the reciprocal of "checked" operation.

Likewise as explained above, the OPCodes for Subtract, Multiply, Divide also exist.

No comments: