1. using System;
  2. using System.Runtime.Serialization;
  3.  
  4. namespace TaskUserDefException
  5. {
  6.     [Serializable]
  7.     public class OverflowIntException : Exception
  8.     {
  9.         public OverflowIntException() { }
  10.         public OverflowIntException(string message) : base(message) { }
  11.         public OverflowIntException(string message, Exception inner)
  12.             : base(message, inner) { }
  13.         protected OverflowIntException(SerializationInfo info, StreamingContext context)
  14.             : base(info, context) { }
  15.     }
  16.  
  17.  
  18.     class Program
  19.     {
  20.         static void Main(string[] args)
  21.         {
  22.             short i = 0;
  23.             try
  24.             {
  25.                 while (true)
  26.                 {
  27.                     if (i < 0)
  28.                         throw new OverflowIntException("Overflow of short integer");
  29.                     Console.WriteLine(i++);
  30.                 }
  31.             }
  32.             catch(OverflowIntException oie)
  33.             {
  34.                 Console.WriteLine(oie.Message);
  35.                 Console.ReadKey();
  36.             }
  37.         }
  38.     }
  39. }

Please note that the above program is not actually necessary. It is only choosen it for didactic reasons.

There is a predefined OverflowException. However, it is only thrown if the keyword checked is used:

  1. using System;
  2.  
  3. namespace TaskUserDefException
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             short i = 0;
  10.             try
  11.             {
  12.                 while (true)
  13.                     Console.WriteLine(checked(i++));  // for throwing of exception, 'checked' is nessecary
  14.             }
  15.             catch (OverflowException oe)
  16.             {
  17.                 Console.WriteLine(oe.Message);
  18.                 Console.ReadKey();
  19.             }
  20.         }
  21.     }
  22. }


Last modified: Friday, 25 October 2019, 9:23 AM