Quick Answer
Handle arithmetic overflow.
Understanding the Issue
This exception occurs when an arithmetic operation exceeds the range of the data type.
The Problem
This code demonstrates the issue:
Csharp
Error
int max = int.MaxValue;
int overflow = max + 1; // Throws in checked context
The Solution
Here's the corrected code:
Csharp
Fixed
// Use checked/unchecked
unchecked {
int overflow = max + 1; // Wraps around
}
// Overflow checking methods
try {
int result = checked(max + 1);
} catch (OverflowException) {
// Handle overflow
}
// Larger data types
long bigNumber = (long)max + 1;
// Math.Clamp (C# 9+)
int safeAdd = Math.Clamp(max + 1, int.MinValue, int.MaxValue);
Key Takeaways
Use checked arithmetic for critical operations and larger types when needed.