How to implement a custom exception class in C#

An exception is an error that occurs at runtime and terminates the normal flow of execution of a program if not handled properly. When exceptions occur, you may not want to reveal the actual stack trace or exception message to the user. Custom exceptions can be used to add clear, meaningful, and user-friendly information to exceptions when errors occur while your program is running.

The base class for all exceptions in .Net is Exception. All of the classes in the exception hierarchy derive directly or indirectly from this class. Note that the System.ApplicationException and System.SystemException classes extend the System.Exception class, which in turn is derived from the System.Object class.

Note that exceptions are just like any other types in .Net.

ApplicationException vs. System.Exception

To create a custom exception class, you should define a type. When designing custom exception classes, you should derive your class from System.Exception and not from ApplicationException. ApplicationException was originally intended to be used to create user defined exceptions, but using it is no longer recommended.

As Microsoft’s documentation states[1]:

You should derive custom exceptions from the Exception class rather than the ApplicationException class.

You should not throw an ApplicationException exception in your code, and you should not catch an ApplicationException exception unless you intend to re-throw the original exception.

References

  1. ^ Microsoft’s documentation states (docs.microsoft.com)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *