When should I create my own custom exception class rather than using a one provided by .Net?
Which base exception class should I derive from and why?
Why create your own exception?
You create your own exception so that when you throw them, you can have specific catches and hence differentiate them from system thrown (unhandled) exceptions.
What class should you derive it from?
Earlier, it was standard practice for custom exceptions to be derived from ApplicationException class but over time, MS recommendations have changed encouraging developers to derive from System.Exception itself rather than ApplicationException
This may seem a bit obvious but you should create an exception when no built in exceptions make sense. Typically I will define a base exception for a library I am working on.
public class MyLibraryException : Exception
{
// .....
}
Then I will create an exception for situations that may arise when using the library.
public class SomethingHorribleException : MyLibraryException
{
// .....
}
Then the client can always know that my library will throw something that inherits MyLibraryException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With