C Sharp User-Defined Exceptions

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# User-Defined Exceptions

C# allows us to create user-defined or custom exception. It is used to make the meaningful exception. To do this, we need to inherit Exception class.

C# user-defined exception example

 
  1. using System;  
  2. public class InvalidAgeException : Exception  
  3. {  
  4.     public InvalidAgeException(String message)  
  5.         : base(message)  
  6.     {  
  7.   
  8.     }  
  9. }  
  10. public class TestUserDefinedException  
  11. {  
  12.     static void validate(int age)  
  13.     {  
  14.         if (age < 18)  
  15.         {  
  16.             throw new InvalidAgeException("Sorry, Age must be greater than 18");  
  17.         }  
  18.     }  
  19.     public static void Main(string[] args)  
  20.     {  
  21.         try  
  22.         {  
  23.             validate(12);  
  24.         }  
  25.         catch (InvalidAgeException e) { Console.WriteLine(e); }  
  26.         Console.WriteLine("Rest of the code");  
  27.     }  
  28. }  

Output:

InvalidAgeException: Sorry, Age must be greater than 18
Rest of the code