.NET provides a hierarchy of exception classes ultimately derived from the Exception base class. However, if none of the predefined exceptions meet your needs, you can create your own exception class by deriving from the 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 Exception base class and includes three constructors.
using namespace System;
public ref class EmployeeListNotFoundException : Exception
{
public:
EmployeeListNotFoundException()
{
}
EmployeeListNotFoundException(String^ message)
: Exception(message)
{
}
EmployeeListNotFoundException(String^ message, Exception^ inner)
: Exception(message, inner)
{
}
};
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
Note
In situations where you're using remoting, you must ensure that the metadata for any user-defined exceptions is available at the server (callee) and to the client (the proxy object or caller). For more information, see Best practices for exceptions.
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
This module explores the process for creating, throwing, and catching customized exceptions in a C# console application. Hands-on activities provide experience customizing exception properties, throwing exceptions, and using the exception properties to mitigate the exception within a catch block.