C Sharp User-Defined Exceptions

C# User-Defined Exceptions

A user-defined or custom exception can be created in C# with a purpose to make a meaningful exception. The Exception class needs to be inherited to create a user-defined exception in C#.

Example:

using System;  
public class InvalidMarksException : Exception  
{  
    public InvalidMarksException(String msg)  
        : base(msg)  
    {  
 
    }  
}  
public class UserDefinedException  
{  
    static void validate(int marks)  
    {  
        if (marks > 100)  
        {  
            throw new InvalidMarksException("Sorry, Marks must be less than 100");  
        }  
    }  
    public static void Main(string[] args)  
    {  
        try  
        {  
            validate(110);  
        }  
        catch (InvalidMarksException e) { Console.WriteLine(e); }  
        Console.WriteLine("Hello World!!");  
    }  
}

Output:

Explanation:

In the above example, we are creating a user-defined exception named “InvalidMarksException” in C#.