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.
Now we will select the ASP.NET 5 Console Application and click on the OK button.
We need to include the following references in our application:
- using System;
- using System.Text.RegularExpressions;
- 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.
- try
- {
- Student newStudent = new Student();
- Console.WriteLine("Enter the student id, Should be numeric : ");
- newStudent.StudentID = Convert.ToString(Console.ReadLine().Trim());
- Console.WriteLine("\n");
-
- Console.WriteLine("Enter the student name, Should be alphabetic : ");
- newStudent.StudentName = Convert.ToString(Console.ReadLine().Trim());
- Console.WriteLine("\n");
-
- ValidateStudent(newStudent);
-
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error:" + ex.Message);
- }
-
- Console.ReadKey();
- }
Initialize the class
The first-class definition for the Student is given below:
- class Student
- {
- public string StudentID { get; set; }
- public string StudentName { get; set; }
- }
-
-
- The second-class definition for the InvalidStudentNameException is given below
-
- [Serializable]
- class InvalidStudentNameException : Exception
- {
- public InvalidStudentNameException(string name) : base(String.Format("Invalid Student Name: {0}", name))
- {
- }
- }
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:
- private static void ValidateStudent(Student std)
- {
- if (!Regex.IsMatch(std.StudentID, "^[0-9]*$"))
- {
- Console.WriteLine(new InvalidStudentIDException(std.StudentID).Message);
- }
-
- if (!Regex.IsMatch(std.StudentName, "^[a-zA-Z]+$"))
- {
- Console.WriteLine(new InvalidStudentNameException(std.StudentName).Message);
- }
- }
Click on F5, execute the project and follow the console window. The output will be:
I hope this article is helpful for the design of a Custom Exception in both interfaces. Thanks for reading this article!
Happy Coding...