Custom Exceptions in C# - Create Custom Exception Class in C#
Custom Exceptions in C# - Create Custom Exception Class in C#
- C# allows us to create user-defined or custom exception and it is used to make the meaningful exception.
- Before using custom exception, we need to inherit Exception class.
Sample Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class InvalidAgeException : Exception
{
public InvalidAgeException(String message)
: base(message)
{
}
}
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be greater than 18");
}
}
public static void Main(string[] args)
{
try
{
validate(12);
}
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
Console.ReadLine();
}
}
Output
