I notice that a number of Java exception classes differ only in the name of the class and do not add any new functionality. Most exceptions for example just seem to override Exception() or Exception(String message)
. This goes against the tenets of inheritance ie:- inherit to add new functionality.
What are some good reasons to create a new Exception class?
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.
You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let's say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.
The Exception class is used for exception conditions that the application may need to handle. Examples of exceptions include IllegalArgumentException , ClassNotFoundException and NullPointerException .
Some people argue that all exceptions should extend from RuntimeException , but if you want to force the user to handle the exception, you should extend Exception instead.
Exceptions are a special case. In their case, the inheritance is not to add new functionality, but to add new classes of errors. This lets your code catch particular kinds of errors while ignoring others.
Say you are writing a large project. You have a Data component, and you have a Display component. They can both fail in various ways, and you want to throw exceptions for these failures. The Display component doesn't care about exceptions arising from the Data component, though, and vice versa. If all the classes just threw Exception
, there'd be no way to figure out where the exception came from. However, if you subclass Exception
with DataException
and GraphicsException
, even though they don't add new functionality, you can now throw and catch those particular types of exceptions, i.e. a graphics component can catch GraphicsException
and not have to deal with data exceptions.
You can catch exceptions by type, and having an exception of a particular type that is otherwise identical to the base Exception class allows you to be precise in your exception handling.
I would argue that it does add new functionality directly by increasing the specificity of exception handling code.
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