Home »
C#
User Defined Exceptions in C#
C# User defined exceptions: In this tutorial, we are going to learn how to create user-defined exceptions in C# with examples?
Submitted by IncludeHelp, on September 21, 2019
C# User-defined exceptions
In C#, we can create our exception class by inheriting base class Exception. Because as we know that Exception is the base class for all types of exceptions in C#.
Here is the example of a user-defined exception,
using System;
class UserDefineException: Exception
{
public UserDefineException(string str)
{
Console.WriteLine(str);
}
}
class Program
{
static void Main()
{
UserDefineException M = new UserDefineException("User Define Exception");
try
{
throw M;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
Output
User Define Exception
Exception of type 'UserDefineException' was thrown.
In the above program, we created a class "UserDefineException" by inheriting the base class "Exception" and created a parameterized constructor, through the user-defined object in "try block" of "Program" class, it is caught in "catch block".
Read more: