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?
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?
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.
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.
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.
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.
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