Should my custom Exceptions Inherit an exception that is similar to them or just inherit from Exception?

Since inheritance is used to specify which exceptions to catch, you should respect this primarily when taking a decision.

Think of an IOException which carries additional information, or a ArgumentException other than ArgumentOutOfRangeException or ArgumentNullException.


Presuming that you really need a custom exception, I would inherit from the Exception most like what you're looking for, rather than just from Exception.

That said, I have found that, under most conditions, using correct wording in you Exception message will normally suffice over creating a whole new exception.

How, for instance is throw new IntOutOfProperRangeException(); significantly different from throw new ArgumentOutOfRangeException("The int value was too large?");


I think it's always safer to create a new Exception type. If you ever need to change how it is handled, it will be easier to find cases where you are or might be handling it. It's a lot easier to find MyException than to find the specific case of ArgumentOutOfRangeException. You seem to be able to provide some extra info in the exception, and it's not too much work to create an exception.

Also I tend to inherit a base application class like MyBaseException, and make sure to add a XML comments for the exception/s.

Tags:

C#

Exception