Custom Exception Type in C#
C# includes the built-in exception types such as NullReferenceException
, MemoryOverflowException
, etc.
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 the 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.
You should not throw an ApplicationException
exception in your code, and you should not catch an ApplicationException
exception unless you intend to re-throw the original exception.
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.
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.
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);
}
}
Thus, you can create custom exception classes to differentiate from system exceptions.