How to use checked to add exception on number overflow in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            checked
            {
                short n = 0;
                for (int i = 0; i < short.MaxValue; i++)
                {
                    n++;
                }
                for (int i = 0; i < short.MaxValue; i++)
                {
                    n++; // overflow error 
                }
            }
        }
    }
}

/*
run:

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in
an overflow.
   at ConsoleApplication_C_Sharp.Program.Main(String[] args) in d:\Conso
leApplication_C_Sharp\ConsoleApplication_C_Sharp\Program.cs:line 18

*/

 



answered Jan 19, 2017 by avibootz

Related questions

1 answer 140 views
1 answer 158 views
1 answer 153 views
1 answer 195 views
1 answer 194 views
...