Saturday, December 6, 2014

Program to create a user-defined Exception

8:02 PM - By azeheruddin khan 0

Explanation: - Apart from Pre-defined exceptions like ArithmeticException or FormatException, we can also have user-defined Exceptions. While dealing with pre-defined exceptions, the Exception manager detects and throws an exception to the appropriate catch block based on the type of exception. But in case of user-defined exception, the programmer has to throw an exception to the user-defined exception class. For this, throw keyword is used. All user-defined and pre-defined exception classes are children of Exception class belonging to System namespace. In the above given program, Userdefined is a user-defined class.

Example:


using System;

namespace UserDefinedException
{
    class Program
    {
        static void Main(string[] args)
        {
            int age;
            try
            {
                Console.Write("enter the age of person:");
                age = Convert.ToInt32(Console.ReadLine());
                if (age < 18 || age > 100)
                {
                    throw new Userdefined("Invalid Age");
                }
            }
            catch (Userdefined u)
            {
                Console.WriteLine(u.m);
            }

            Console.ReadLine();

        }
    }

    class Userdefined : Exception
    {
        public string m;
        public Userdefined(string s)
        {
            m = s;
        }
    }

}


Output:





About the Author

I am Azeheruddin Khan having more than 6 year experience in c#, Asp.net and ms sql.My work comprise of medium and enterprise level projects using asp.net and other Microsoft .net technologies. Please feel free to contact me for any queries via posting comments on my blog,i will try to reply as early as possible. Follow me @fresher2programmer
View all posts by admin →

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

adsense

© 2014 Fresher2Programmer. WP Theme-junkie converted by Bloggertheme9
Powered by Blogger.
back to top