English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Custom Exception

C # includes built-in exception types such as NullReferenceException, MemoryOverflowException, and others. However, when the business rules of your application are violated, you usually want to throw an exception. Therefore, you can create a custom exception class by deriving from the ApplicationException class.

.Net version1Starting from .Net v

For example, in a school application, create the InvalidStudentNameException class that does not allow any student's name to contain any special characters or numeric values.

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, as long as the program name contains special characters or numbers, InvalidStudentNameException can be triggered in the program. Use the throw keyword to throw the exception.

class Program
{"}}
    static void Main(string[] args)
    {"}}
        Student newStudent = null;
          
        try
        {"}}               
            newStudent = new Student();
            newStudent.StudentName = "James00"7";
            
            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

Therefore, you can create custom exception classes to distinguish between system exceptions.