Let say I have this interface A that is implemented by multiple vendors:
interface A
{
void x();
void y();
}
However, I want vendors to be able to throw exceptions to signal something has failed and potentially the method could thrown a RuntimeException. In each case, the code that calls these methods should handle the failure and continue. Just because 1 vendor throws an NPE, I don’t want the system to come crashing down. Instead of leaving it up to the person calling the method (or really down the line maintainence), I would like to make sure each call will catch all exceptions by declaring each method as:
void x() throws Exception;
but this is generally bad practice (PMD doesn’t like it and generally I agree with the rule for concrete methods) so I wonder is this an exception to the rule or is there a better way?
Let me be clear, I’m looking for a solution where the caller of the interface is forced to handle all exceptions (including RuntimeExceptions).
To further detail my environment, all of this is running within an OSGi framework. So each vendor packages their code in a bundle and OSGi will handle all exceptions to prevent the entire system from crashing. What I’m really looking at are OSGi service interfaces that will be called by some core bundle. What I want to make sure is that when I iterate through all of the services, one service doesn’t throw an NPE and stop the process that is executing. I want to handle it more gracefully by catching all exceptions thrown from the service so the other provided services are still managed.
Create your own Exception class ie.
MySeviceExceptionand throw it from the interface. The idea here is to throw meaningful exceptions so don’t be afraid of creating many custom exception classes if that provides most readability and maintainability for your purposes. You can catch the vendor detailed exceptions in the downstream and wrap them as your custom exception so that the upstream flow does not have to deal with vendor specific exceptions.As a rule of thumb never catch
Errors, always catchExceptionsand deal with it!