C# Tips & Tricks #33 – Why doesn’t this cause an Exception ?

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

Leave A Reply

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

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
There are times when you might get the below error when you have multiple projects with-in your Visual Studio solution....