C# checked

main program


 public static void test1()
 {
     Console.WriteLine("\nCHECK UNCHECK");
     uint a = uint.MaxValue;
     unchecked
     {
         Console.WriteLine(a + 3);  // output: 2
     }
     try
     {
         checked
         {
             Console.WriteLine(a + 3);
         }
     }
     catch (OverflowException e)
     {
         Console.WriteLine(e.Message);  // output: Arithmetic operation resulted in an overflow.
     }
 }
 

console

2 Arithmetic operation resulted in an overflow.

public static void test2()
{
    double a = double.MaxValue;
    int b = unchecked((int)a);
    Console.WriteLine(b);  // output: -2147483648

    try
    {
        b = checked((int)a);
    }
    catch (OverflowException e)
    {
        Console.WriteLine(e.Message);  // output: Arithmetic operation resulted in an overflow.
    }
}
 

console

2147483647 Arithmetic operation resulted in an overflow.