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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...