top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are Custom Exceptions in C#?

0 votes
203 views
What are Custom Exceptions in C#?
posted Apr 24, 2017 by Pooja Bhanout

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

We have seen built-in exception classes at various places. However, you often like to raise an exception when the business rule of your application gets violated. So, for this you can create a custom exception class by deriving Exception or ApplicationException class.

The .Net framework includes ApplicationException class since .Net v1.0. It was designed to use as a base class for the custom exception class. However, Microsoft now recommends Exception class to create a custom exception class.

For example, create InvalidStudentNameException class in a school application, which does not allow any special character or numeric value in a name of any of the students.

Example: ApplicationException

class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
}

[Serializable]
class InvalidStudentNameException : Exception
{
    public InvalidStudentNameException()
    {

    }

    public InvalidStudentNameException(string name)
        : base(String.Format("Invalid Student Name: {0}", name))
    {

    }

}

Now, you can raise InvalidStudentNameException in your program whenever the name contains special characters or numbers. Use the throw keyword to raise an exception.

Example: throw custom exception

class Program
{
    static void Main(string[] args)
    {
        Student newStudent = null;

        try
        {               
            newStudent = new Student();
            newStudent.StudentName = "James007";

            ValidateStudent(newStudent);
        }
        catch(InvalidStudentNameException ex)
        {
            Console.WriteLine(ex.Message );
        }


        Console.ReadKey();
    }

    private static void ValidateStudent(Student std)
    {
        Regex regex = new Regex("^[a-zA-Z]+$");

        if (regex.IsMatch(std.StudentName))
             throw new InvalidStudentNameException(std.StudentName);

    }
}

Output:
Invalid Student Name: James000

Thus, you can create custom exception classes to differentiate from system exceptions.

Points to Remember :
Exception is a base class for any type of exception class in C#.
Derive Exception class to create your own custom exception classes.

answer Apr 25, 2017 by Shivaranjini
...