As we learned in previous sections, c# has provided many built-in exception classes to handle runtime or unexpected errors in the application. In case if none of the predefined exception classes meet your needs, then you can create your own exception classes by deriving from
Exception base class.
While creating your own user-defined exception class, you need to ensure that the end of class name contains the “Exception” word, and it must be derived from
Exception base class. After creating your own custom exception class, you need to implement the three common constructors, as shown in the following example.
Following is the example of creating a new exception class named “TutlaneCustomException” by deriving from
Exception base class and including three constructors.
throw keyword, we can raise an exception using TutlaneCustomException class in our program based on our requirements.
Following is the example of creating a custom exception class (TutlaneCustomException) and throwing exceptions using a custom exception class in c#.
If you observe the above example, we created a custom exception class TutlaneCustomException by deriving from
Exception base class, and we used a
throw keyword to raise an exception.
When we execute the above example, we will get the result below.
This is how you can create your own custom exception classes by deriving from
Exception base class in c# based on our requirements.