find and solve || findandsolve.com
Please wait.....

Custom Exception Example in c#

When creating our own exceptions, end the class name of the user-defined exception with the word "Exception". custom exception is used to make the meaningful exception.

C# user-defined exception example

using System;  
public class InvalidAgeException : Exception
{
    public InvalidAgeException(String message)
        : base(message)
    {
    }
}
public class TestUserDefinedException
{
   public static void validate(int age)
    {
        if (age < 20)
        {
            throw new InvalidAgeException("Sorry, Age must be greater than 20");
        }
    }
    public static void Main(string[] args)
    {
        try
        {
            validate(12);
        }
        catch (InvalidAgeException e) { Console.WriteLine(e); }
        Console.WriteLine("Reset of the code");     }

Output

InvalidAgeException: Sorry, Age must be greater than 20

Reset of the code