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 our needs, then we can create our own exception classes by deriving from
Exception base class.
While creating our own user-defined exception class, we need to make sure that the end of class name will contain the “Exception” word, and it must be derived from
Exception base class. After creating our own custom exception class, we 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 as shown below.
This is how we can create our own custom exception classes by deriving from
Exception base class in c# based on our requirements.