Read the syntax
checked makes overflowing integral arithmetic throw OverflowException. Its effect applies to operations textually inside the checked context, not automatically to code called from it. Use a .NET 8+ console project; replace Program.cs with this C# example.
The runtime value cannot fit in Int32 after incrementing, so evaluation throws before assigning result.
Syntax
checked { int result = value + 1; }Examples
Checked Integer Overflow
Use a .NET 8+ console project; replace Program.cs with this C# example.
using System;
int value = int.MaxValue;
try
{
int result = checked(value + 1);
Console.WriteLine(result);
}
catch (OverflowException)
{
Console.WriteLine("overflow rejected");
}- Expected output: overflow rejected
- The runtime value cannot fit in Int32 after incrementing, so evaluation throws before assigning result.
- Use checked at boundaries where overflow must not wrap silently.
Best practices
- Use checked at boundaries where overflow must not wrap silently.
- Choose a wider or arbitrary-precision type when large results are legitimate.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference