Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto activate eclipse java warning "unnecessary declaration of thrown exception" without getting false positives?

I hate functions that declare to throw exceptions that are not thrown by this functions in any case. This happens in refactorings if throw statements are removed in the function body without removing it from the throws definitions.

Thats why I activated the setting Java -> Compiler -> Errors/Warnings -> Unnecessary code -> Unnecessary declaration of thrown exception.

enter image description here

This leads to false positive warnings if exceptions are defined in interfaces or super methods. If implementation A of the interface does not throw one exception type, but implementation B does, eclipse warns about the unnecessary declaration in implemantation A. Thats equally for super and overriden methods. Thats why I activate the suboption "Ignore in overriding and implementing methods".

Perfeclty fine till here. But I have the oposite case. The overridden method throws a exception type, that is not used in the super method. See this minimal example:

class Vehicle {
    protected int getStatus() throws GeneralException, StatusException {
        throw new GeneralException("One exception type in super type only");
    }
}

class Car extends Vehicle {
    @Override
    protected int getStatus() throws GeneralException, StatusException {
        throw new StatusException("Special case, that gets special handling");
    }
}

Now StatusException in Vehicle is warned in eclipse.

enter image description here

Of course one could argue that this is bad design etc., but from a pragmatic point of view this will happen again and most probably one can accept to not change the architecture, but to simply add the new exception type to the super type. But howto get rid of the false positive warning in this case? Of course one could use the suboption with the javadoc, but this would also ignore most real positive hits. Another option is to add the SuppressWarning annotation "unused", but other users could get unneeded warnings for that suppression.

like image 443
jan Avatar asked Oct 07 '13 08:10

jan


1 Answers

Personally I'd activate the second option under the warning setting: "Ignore exceptions documented..." and just document those:

/**
 * @throws GeneralException when general stuff goes wrong
 * @throws StatusException when status stuff goes wrong
 */
protected int getStatus() throws GeneralException, StatusException {
    throw new GeneralException("One exception type in super type only");
}

Maybe include a slightly more useful explanation, but it'll basically boild down to this.

like image 126
Joachim Sauer Avatar answered Oct 02 '22 08:10

Joachim Sauer