Creating Custom Exceptions In C#

User defined exceptions can be created by deriving from the System.ApplicationException class or from any other system defined class. You can also derive Exceptions from these user-defined classes. The ultimate thing is that the new Exception class should be derived (directly or indirectly) from the Exception class.
 
class MyException : ApplicationException
{
    public MyException(string Message) : base(Message)
    {
 
    }
}
 
Raising Exceptions
 
Use the throw statement to raise your exceptions. This process requires the creation of a new object of the appropriate Exception class.
 
throw new(MyException(“My Exception was thrown”));
 
Even the system defined exceptions can be thrown in this fashion.
 
Note: Never create and throw an object of System.Exception class.
Scroll to Top