Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

exception

I am creating some custom exceptions in my application.

If I have an exception that gets thrown after testing the state of an argument, Or I have an Exception that gets thrown after testing that an int is within the proper range, should my exceptions inherit ArgumentException and IndexOutOfRangeException or should they just inherit Exception?

like image 393
Sruly Avatar asked Jun 23 '09 13:06

Sruly


People also ask

What are some of the points you should consider before creating custom exceptions?

Questions to ask yourself:Who will be catching it? If no one, then you don't really need a custom exception. Where will you be throwing it? Is there enough context readily available, or will you need to catch and re-throw several times before the exception is useful to the final catcher?

Which is the base class should be inherited for defining our own custom exception filter?

When creating custom exception classes, they should inherit from the System. Exception class (or any of your other custom exception classes from the previous section). The class name should end with the word Exception, and it should implement at least the three common constructors of exception types.

Should you inherit from std exception?

If you want to make use of the string constructor, you should inherit from std::runtime_error or std::logic_error which implements a string constructor and implements the std::exception::what method.

Should I create custom exceptions?

You should only implement a custom exception if it provides a benefit compared to Java's standard exceptions. The class name of your exception should end with Exception. If an API method specifies an exception, the exception class becomes part of the API, and you need to document it.


1 Answers

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.

like image 97
Lucero Avatar answered Sep 26 '22 06:09

Lucero