Introduction

Here we will see how to handle a Custom Exception class with both interfaces (Exception, ApplicationException) using C#.

Let’s develop a simple C# console application to show a Custom Exception class.

Getting Started

In ASP.NET 5 we can create console applications. First, open Visual Studio 2015 and create a new console application using File-> New-> Project.
image1
Now we will select the ASP.NET 5 Console Application and click on the OK button.
image2
We need to include the following references in our application:
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.Collections.Generic;

In the main method, I have created 3 classes and 1 method

1. Student – To define class members.
2. InvalidStudentNameException = Initialize with exception interface in the class.
3. InvalidStudentIDException = Initialize with Application Exception interface in the class.
4. ValidateStudent – Validate the value in this method.
  1. try
  2. {
  3. Student newStudent = new Student();
  4. Console.WriteLine("Enter the student id, Should be numeric : ");
  5. newStudent.StudentID = Convert.ToString(Console.ReadLine().Trim());
  6. Console.WriteLine("\n");
  7. Console.WriteLine("Enter the student name, Should be alphabetic : ");
  8. newStudent.StudentName = Convert.ToString(Console.ReadLine().Trim());
  9. Console.WriteLine("\n");
  10. ValidateStudent(newStudent);
  11. }
  12. catch (Exception ex)
  13. {
  14. Console.WriteLine("Error:" + ex.Message);
  15. }
  16. Console.ReadKey();
  17. }

Initialize the class

The first-class definition for the Student is given below:
  1. class Student
  2. {
  3. public string StudentID { get; set; }
  4. public string StudentName { get; set; }
  5. }
  6. The second-class definition for the InvalidStudentNameException is given below
  7. [Serializable]
  8. class InvalidStudentNameException : Exception
  9. {
  10. public InvalidStudentNameException(string name) : base(String.Format("Invalid Student Name: {0}", name))
  11. {
  12. }
  13. }
The third-class definition for the InvalidStudentIDException is given below:

[Serializable]
class InvalidStudentIDException : ApplicationException
{
public InvalidStudentIDException(string Id) : base(String.Format("Invalid Student Id: {0}", Id))
{
}
}

Initialize the Method

The method definition for ValidateStudent() is given below:
  1. private static void ValidateStudent(Student std)
  2. {
  3. if (!Regex.IsMatch(std.StudentID, "^[0-9]*$"))
  4. {
  5. Console.WriteLine(new InvalidStudentIDException(std.StudentID).Message);
  6. }
  7. if (!Regex.IsMatch(std.StudentName, "^[a-zA-Z]+$"))
  8. {
  9. Console.WriteLine(new InvalidStudentNameException(std.StudentName).Message);
  10. }
  11. }
Click on F5, execute the project and follow the console window. The output will be:
image3
I hope this article is helpful for the design of a Custom Exception in both interfaces. Thanks for reading this article!
Happy Coding...