try
{
int i = 1;
Console.WriteLine(i + int.MaxValue);
Console.ReadLine();
}
catch (Exception Ex)
{
Console.WriteLine("Crazy operation");
}You will be surprised to see that the above code snippet gets executed without any exception. Apparently the framework masks any overflow exception that are raised when overflow exceptions happen during addition or subtraction.
Now the question is how to prevent this from happening.
try
{
checked
{
int i = 1;
Console.WriteLine(i + int.MaxValue);
Console.WriteLine(int.MinValue - i);
Console.ReadLine();
}
}
catch (Exception Ex)
{
Console.WriteLine("Crazy operation");}
Using check operator ensures that exceptions are raised when overflow happens.
Friday, August 1, 2008
Interesting Arithmetic Operations
I came across an interesting piece of code snippet. You are invited to take the guess of the result.
Subscribe to:
Comments (Atom)