Note that there are some explanatory texts on larger screens.

plurals
  1. POClean-up of exceptions declared in interface but not thrown by implementation
    primarykey
    data
    text
    <p>I have a lot of Java interfaces with only one main implementation (not counting mocks and stubs).</p> <p>Over time, the interface and its implementation evolve, including the exceptions that are thrown by some methods.</p> <p>The problem is that when we add an exception in the implementation, the compiler reminds us to add the exception on the interface. But when an exception is not thrown anymore by the implementation, there is a warning reminding us to remove the exception declaration on the implementation, but we often forget to remove it from the interface.</p> <p>And so we end up, in the client code of the interface, dealing with exceptions that are never actually thrown.</p> <p>Step 1, we have an exception in the implementation, it is propagated up the chain:</p> <pre><code>interface Service { void doSomething() throws MyException; } class ServiceImpl implements Service { void doSomething() throws MyException { if (dummyCondition) { throw new MyException("oops"); } System.out.println("hello world"); } } class Client { @Inject Service service; void clientCode() { try { service.doSomething(); } catch(MyException e) { logger.error("oops", e); } } } </code></pre> <p>Step 2, the exception is not thrown anymore by the implementation, but we forgot to clean the interface, and so don't realize the catch is not useful anymore:</p> <pre><code>interface Service { void doSomething() throws MyException; } class ServiceImpl implements Service { void doSomething() { if (dummyCondition) { logger.warning("actually, don't throw, just log 'oops'"); } System.out.println("hello world"); } } class Client { @Inject Service service; void clientCode() { try { service.doSomething(); } catch(MyException e) { logger.error("oops", e); // we'll never get there. } } } </code></pre> <p>Ideally, I would like a warning on the interface saying something like "Exception declared but not thrown by any known implementation".</p> <p>Is there a way to detect those declared-but-never-thrown exceptions, in Eclipse or with a source code analysis tool, to be able to do some clean-up ?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload