Cloud Training (Online)




Checked Block in .NET – Why doesn’t this cause an Exception in Visual Studio ?

This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual Studio.

I was trying to run the below code snippet in Visual Studio 2010 .

     int Number1 = 320000;

     int Number2 = 320000;

     int Number3 = Number1 * Number2 ;

     MessageBox.Show(Number3.ToString());

The code resulted in the value – 797966336 without being showing the error or the correct value .


Just found that If you want an exception to be raised on this occassion , then use the following 2 options as below .

1. Checked Block

Checked
{
      int Number1 = 320000;

      int Number2 = 320000;

      int Number3 = Number1  * Number2 ;

      MessageBox.Show(Number3.ToString());
}

2. Enable the checked compiler option in Visual Studio Project Properties

To set the compiler option in the Visual Studio 2010 .

1. Right Click on the Project and open Properties.

Checked Block in .NET

2. Click the Build Property Tab page

3. Click the Advanced Button near the Output.

Checked Block in .NET



4.Check the Property “Check for Arithmetic Overflow/Underflow” and Click ok .

Checked Block in .NET

Now run the same code again , you should be able to raise an exception

OverFlow Exception was unhandled .

Arithmetic operation resulted in an overflow.

Checked Block in .NET