C# User-defined exception handling sample program

Project

using System;

namespace Exceptions
{
    class UserDefinedException
    {
        class InvalidAgeException : Exception
        {
            public InvalidAgeException(String message) : base(message)
            {
            }
        }

        public static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Enter your name");
                string name = Console.ReadLine();

                Console.WriteLine("Enter your age");
                int InputAge = int.Parse(Console.ReadLine());

                if (InputAge < 18)
                {
                    throw new InvalidAgeException("\nSorry, 
                  Age must be greater than 18 for the selection process");
                }
                else
                {
                    Console.WriteLine("You are selected..");
                }
            }
            catch (InvalidAgeException e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("Thank you");
            Console.ReadKey();

        }//Main..
    }
}


Output

Enter your name
John
Enter your age
17

Exceptions.UserDefinedException+InvalidAgeException:
Sorry, Age must be greater than 18 for the selection process
   at Exceptions.UserDefinedException.Main(String[] args) in C:\ProjectSamples\ClassRoomSamples\Exceptions\UserDefinedException.cs:line 30
Thank you

No comments:

Post a Comment