BLOG.CSHARPHELPER.COM: Control overflow behavior with checked and unchecked in C#
Control overflow behavior with checked and unchecked in C#
C# handles overflow with different data types differently. You can control this to some extent with the checked and unchecked keywords.
If you execute code inside a checked block and an int or long operation causes an overflow, the block throws an error.
If you execute code inside an unchecked block (or no block--this is the default behavior) and an int or long operation causes an overflow, the value simply overflows and creates a gibberish value without giving you any indication that there is a problem.
The following code uses longs to try to calculate the factorial function. If there is an overflow, the checked block throws an error.
private string LongFactorial(long N) { // Long obeys checked and unchecked. try { checked { long result = 1; for (long i = 2; i <= N; i++) result *= i; return result.ToString(); } } catch (Exception ex) { return ex.ToString(); } }
Try changing this to an unchecked block or removing the checked block to see what happens.
Floats and doubles ignore checked and return Infinity.
Decimal ignores unchecked and always throws an exception.
Nice and consistent, huh?
The following table summarizes how the data types behave.
Data Type
Default
Checked
Unchecked
int
Gibberish
Exception
Gibberish
long
Gibberish
Exception
Gibberish
decimal
Exception
Exception
Exception
float
Infinity
Infinity
Infinity
double
Infinity
Infinity
Infinity
The moral is to be aware of the kinds of failures a data type might produce. Unless you really don't care, use checked to catch errors with ints and longs, always catch errors with decimals, and look for Infinity with floats and doubles.
Comments