I'm defining a new interface API... admittedly not something I do all that often. I'd like to define the interface methods to throw an Exception to allow some flexibility for the implementers. They can then choose to throw an Exception, throw a more specific subclass of Exception, or throw nothing at all. I've read a couple of times that while its good to allow implementing classes this flexibility, it's also bad to define the interface method with "throws Exception". Instead, it's recommended to subclass Exception (e.g. MyException) and throw the subclass. The explanations for this practice were lacking in detail, so can someone elaborate on this best practice please? Thanks.
Yes, the abstract methods of an interface can throw an exception.
Don't Catch Throwable You can use it in a catch clause, but you should never do it! If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application.
so i would better call it is a bad practice to handle RuntimeException instead of calling it is bad practice to handle Unchecked Exception. sometimes handling a unchecked exception which a programmer can predict is a good idea.
I can appreciate trying to give the implementers some flexibility, but the exception is part of the API, so you should put some thought into what (checked) exception(s) makes sense.
By saying throws Exception
, you are not helping the clients of the interface understand what kinds of failures are expected to give them a chance to react to them appropriately. You can consider akin to accepting a method parameter of Object
to allow implementers to decide what arguments they can accept. Its good for the implementer, but a nightmare for the clients of the interface.
Better have an idea what exceptions you need to throw later. There's the so called Liskov substitution principle, which recommends not to throw exceptions in subclasses that would not be thrown by the super class.
Liskov substitution principle aka. design by contract: http://en.wikipedia.org/wiki/Liskov_substitution_principle
If you are uncertain which Exception need to be thrown, use "throws Exception" (even if it is uncool). Just do not allow unexpected behaviour by implementing classes when they throw exceptions where they weren't planned by you.
The worst case would be a programmer who desperately throws runtime exceptions because of a lack of throws-declarations.
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