C#idiomatic C#
how-to-create-user-defined-exceptionsstandard/exceptions

Core library

How to create user-defined exceptions

Learn how to create user-defined exceptions, which are an alternative to the hierarchy of exception classes derived from the Exception base class in .NET.

  • page standard/exceptions/how-to-create-user-defined-exceptions
  • updated 08/10/2022

.NET provides a hierarchy of exception classes ultimately derived from the System.Exception base class. However, if none of the predefined exceptions meet your needs, you can create your own exception class by deriving from the System.Exception class.

When creating your own exceptions, end the class name of the user-defined exception with the word "Exception", and implement the three common constructors, as shown in the following example. The example defines a new exception class named EmployeeListNotFoundException. The class is derived from the System.Exception base class and includes three constructors.

sample · csharpsamples/snippets/csharp/VS_Snippets_CLR/dg_exceptionDesign/cs/example2.cs14

csharp
//<snippet14>
using System;

public class EmployeeListNotFoundException : Exception
{
    public EmployeeListNotFoundException()
    {
    }

    public EmployeeListNotFoundException(string message)
        : base(message)
    {
    }

    public EmployeeListNotFoundException(string message, Exception inner)
        : base(message, inner)
    {
    }
}
//</snippet14>

public class TestExample
{
    public static void Main()
    {
        Exception ex = new();

        _ = new EmployeeListNotFoundException();
        _ = new EmployeeListNotFoundException("Hi!");
        _ = new EmployeeListNotFoundException("Hi!", ex);
    }
}

sample · vbsamples/snippets/visualbasic/VS_Snippets_CLR/dg_exceptionDesign/vb/example2.vb14

vb
'<snippet14>
Public Class EmployeeListNotFoundException
    Inherits Exception

    Public Sub New()
    End Sub

    Public Sub New(message As String)
        MyBase.New(message)
    End Sub

    Public Sub New(message As String, inner As Exception)
        MyBase.New(message, inner)
    End Sub
End Class
'</snippet14>

Public Class TestExample
    Public Shared Sub Main()
        Dim e1, e2, e3 As EmployeeListNotFoundException
        Dim ex As New Exception()

        e1 = New EmployeeListNotFoundException()
        e2 = New EmployeeListNotFoundException("Hi!")
        e3 = New EmployeeListNotFoundException("Hi!", ex)
    End Sub
End Class

See also