Mark code block as checked : checked « Data Type « C# / CSharp Tutorial






using System;

class MainClass
{
    public static void Main()
    {
        byte val1 = 200;
        byte val2 = 201;
        byte sum = (byte) (val1 + val2);   // no exception
        checked
        {
            byte sum2 = (byte) (val1 + val2);      // exception
        }
    }
}
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
   at MainClass.Main()








2.48.checked
2.48.1.Using checked and unchecked
2.48.2.Numeric Addition overflow for a byte
2.48.3.Mark code block as checked
2.48.4.A Checked Block Example