Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net exceptions

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?

like image 248
Moon Avatar asked Feb 14 '26 05:02

Moon


2 Answers

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

like image 196
Jagmag Avatar answered Feb 16 '26 20:02

Jagmag


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.

like image 32
ChaosPandion Avatar answered Feb 16 '26 19:02

ChaosPandion