In C# how do I define my own Exceptions?
From Microsoft's .NET Core 3.0 docs:
To define your own exception class:
Define a class that inherits from Exception. If necessary, define any unique members needed by your class to provide additional information about the exception. For example, the ArgumentException class includes a ParamName property that specifies the name of the parameter whose argument caused the exception, and the RegexMatchTimeoutException property includes a MatchTimeout property that indicates the time-out interval.
If necessary, override any inherited members whose functionality you want to change or modify. Note that most existing derived classes of Exception do not override the behavior of inherited members.
Determine whether your custom exception object is serializable. Serialization enables you to save information about the exception and permits exception information to be shared by a server and a client proxy in a remoting context. To make the exception object serializable, mark it with the SerializableAttribute attribute.
Define the constructors of your exception class. Typically, exception classes have one or more of the following constructors:
Exception(), which uses default values to initialize the properties of a new exception object.
Exception(String), which initializes a new exception object with a specified error message.
Exception(String, Exception), which initializes a new exception object with a specified error message and inner exception.
Exception(SerializationInfo, StreamingContext), which is a protected constructor that initializes a new exception object from serialized data. You should implement this constructor if you've chosen to make your exception object serializable.
Example:
using System;
using System.Runtime.Serialization;
[Serializable()]
public class NotPrimeException : Exception
{
private int _notAPrime;
public int NotAPrime { get { return _notAPrime; } }
protected NotPrimeException() : base()
{ }
public NotPrimeException(int value) : base(String.Format("{0} is not a prime number.", value))
{
_notAPrime = value;
}
public NotPrimeException(int value, string message) : base(message)
{
_notAPrime = value;
}
public NotPrimeException(int value, string message, Exception innerException) : base(message, innerException)
{
_notAPrime = value;
}
protected NotPrimeException(SerializationInfo info, StreamingContext context) : base(info, context)
{ }
}
Usage in throw:
throw new NotPrimeException(prime, "This is not a prime number."));
Usage in try/catch:
try
{
...
}
catch (NotPrimeException e)
{
Console.WriteLine( "{0} is not prime", e.NotAPrime );
}