User Defined Exception Class in C#

In this Section you will learn:

  • How to create user defined exception in c#?
  • What is Custom Exception?
  • How to handle user defined exception? Programming Example

How to Create User Defined Exception in C#

In the previous chapter we have learned about try catch and finally keyword which are the basic building block of exception handling. In this chapter we will learn a new keyword “throw” in exception handling. This keyword is used for creating custom exception class or creating user defined exception class.

While creating custom exception class it is best practice to keep class name with the end of Exception word. For example, OutofStockException, NumberNotFoundException, IamHeroException etc.

Let’s see a programming example first then we will explain how can you create your own exception and use it in your program.

  • Programming Example of Custom Exception Class in C#

    Output Explain

    Output 1

    Input : 4
    It will not raise any exception and shows output.

    Welcome to Shopping Site:
    How many headphone you want to buy (Total 10 in Stock):
    Congratulations! You have bought 4 headphones


    Output 2

    Input : 12
    It will raise OutofStockException and handled by OutofStockException catch block.

    Welcome to Shopping Site:
    How many headphone you want to buy (Total 10 in Stock):
    OutofStockException Generated: The number of item you want to buy is out of stock. Please enter total item number within stock



    1. In this example we have created a custom exception class OutofStockException which is catches by catch block when user enter larger number than the stock available. All the user defined exception class must be derived from its base class Exception.


    2. All the exception class must have a constructor. However, you may define numbers of constructors based on your requirement. Here we have created only one constructors to keep program simple and easy to understand. This constructors will be used later to throw a string message.


    3. Now in the main method, we asks user for buying a headphone and asks the total number of headphone he/she want to buy. If the number of buying headphone is equal or less than the stock a congratulations message appear but if the total number of buying headphone is larger than stock available it raise OutofStockException.



    In this chapter we have learned how to create and throw custom exception or user defined exception in C#. In the next chapter we will learn about System Exceptions with programming Example.

    Leave a Reply

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