C# Checked and Unchecked Exceptions - What are checked exceptions in C# ?
C# Checked Exceptions - What are checked exceptions in C# ?
- C# provides checked and unchecked keyword to handle integral type exceptions.
- Respectively checked and unchecked keywords specify checked context and unchecked context.
- In checked context, arithmetic overflow raises an exception whereas, in an unchecked context, arithmetic overflow is ignored and result is truncated.
Sample Code for Checked Exception
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exception
{
class Program
{
static void Main(string[] args)
{
checked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output

Sample Code for UnChecked Exception
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exception
{
class Program
{
static void Main(string[] args)
{
unchecked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
Console.ReadLine();
}
}
}
}
Output
