Overflow exception in C#

What is Checked and Unchecked Statement?

Checked and Unchecked statements are used to check the memory overflow exceptions. The checked keyword is used to check the overflow for integral-type arithmetic operations and conversions. Overflow occurs when the value of a variable exceeds the required original length of the variable. The unchecked keyword ignores the overflow-checking of the integral-type arithmetic operations and conversions. Arithmetic overflow exceptions are raised in a checked context; whereas, in the case of unchecked context, arithmetic overflow is ignored and the program displays the truncated integers from the result.

The following code snippet shows an example of checked and unchecked statements:

byte number1, number2;
byte result;
number1 = 127;
number2 = 127;
try
{
result = unchecked((byte)(number1 * number2));
Console.WriteLine("Unchecked result: " + result);
result = checked((byte)(number1 * number2));
Console.WriteLine("Checked result: " + result);
}
catch(OverflowException exc)
{
Console.WriteLine(exc);
}

In the preceding code snippet, you can see that the OverflowException class is used to catch the overflow exception.



Write a comment


Name Email Message