How to Create Custom Exception in C# .net program? Use of it?

(Last Updated On: February 6, 2017)

Implementation of user defined or custom exception in C# .net programming is simple and is implemented by extending system Exception class. We’ll answer concept of run time custom exception with a program example in C#.

Custom Exception Class

Custom Exception class is nothing but a user defined class which is derived from System Exception class. Here are steps

  • Derive a Custom class from System Exception class.
  • Create a constructor of custom class with error message parameter and pass it to the base class (System Exception class).
  • Throw and catch custom exception message in try catch block in C# wherever is required.



Complete C# Program for Custom Exception

Let’s understand the concept with simple example. Below program will accept a string from user and if the string is alphanumeric, program will be processed or else it will throw a custom exception that “Only Alphanumeric string is allowed”




This custom exception handling in C# interview question can also be asked as how to create user defined exception in C# or why we use custom exception or why do we need it in C# project or how to throw or handle custom run time exception message etc.


Why do we need Custom Exception in C# applications?

There are tons of exceptions available in C# .net framework e.g. FileFormatException, FileNotFoundException and DriveNotFoundException etc. However, sometime we need to write our own custom exception class in an application. For example, let’s say during database processing, error code is thrown for resource is busy or table is full etc.  and since, error code may not be understandable to customer, so we may want to throw meaning full run time exception, so, customer or end user can understand it.