Introduction
When you are dealing with the integer values which are in higher amounts, you might arrive at a situation where the program gives you the wrong output.
First, we need to know the ranges of every datatype so that the explanation will be easier.
Datatype | Range |
int (32-bit signed) | -2,147,483,648 to 2,147,483,648 |
long (64-bit signed) | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
So, when we use int datatype and if value exceeds the range, the value is taken as -1.
Static assignment of values higher than the range will show compile errors, but if the value is assigned dynamically the compiler doesn’t show any errors.
Whenever arithmetic overflow occurs, the C# compiler is made capable of internally handling the result and sends out an unexpected output.
Example 1 - Code Snippet
- int maxValue = 2147483648;
The code will be not compiled as we see a static assignment which is beyond the range. The C# compiler is capable of checking the range and also provides an alternative solution too.
The below compiler error message is thrown.
Example 2 - Code Snippet
- int maxValue = 2147483647;
- maxValue += 1;
- Console.WriteLine(maxValue);
Output
-2147483648;
The output is completely unexpected as the value crossed the range of “int”.
Checked Keyword
So, we face a problematic situation now and we need to handle these kinds of situations.
This is called “Arithmetic Overflow”.
C# provides “checked” keyword to handle this issue.
The checked way of the same implementation would be like below.
Code Snippet
- int maxValue = 2147483647;
- int output = -10;
- try {
- output = checked(maxValue + 10);
- } catch (OverflowException e) {
- Console.WriteLine("Output = " + output);
- }
Output
-10
Conclusion
- Arithmetic Overflow exception was handled successfully.
- Based on your need, you can alter the statement inside catch block to match your requirements.