Check user input with try catch statement - CSharp Custom Type

CSharp examples for Custom Type:try catch finally

Description

Check user input with try catch statement

Demo Code

using System;//from   ww  w . j a  va  2 s  . c  o  m
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
   static void Main(string[] args)
   {
      try
      {
         // Text input of date
         Console.Write("Enter date: ");
         string input = Console.ReadLine();
         // Conversion to DateTime object
         DateTime enteredDate = Convert.ToDateTime(input);
         // Some calculations
         DateTime followingDay = enteredDate.AddDays(1);
         DateTime previousDay  = enteredDate.AddDays(-1);
         // Outputs
         Console.WriteLine("Entered day  : " + enteredDate.ToLongDateString());
         Console.WriteLine("Following day: " + followingDay.ToLongDateString());
         Console.WriteLine("Previous day : " + previousDay.ToLongDateString());
      }
      catch (Exception)
      {
         Console.WriteLine("Incorrect input");
      }
   }
}

Result


Related Tutorials