Unnecessary throws

MSAL

Remove unnecessary throws declarations. This recipe will only remove unused, checked exceptions if:

  • The declaring class or the method declaration is final.
  • The method declaration is static or private.
  • The method overrides a method declaration in a super class and the super class does not throw the exception.
  • The method is public and the exception is not documented via a JavaDoc as a @throws tag.

The throws declaration is retained on overridable methods (package-private and protected methods on non-final classes), and on public methods overridden within the same source file, so that a subclass override which does throw the exception keeps compiling. Overrides in other source files cannot be detected without a scanning recipe and are therefore not accounted for.

A throws declaration is also retained when the method body contains a call whose type does not fully resolve, because such a call may throw the exception.

When a throws declaration is removed, any @throws or @exception JavaDoc tag documenting that exception is removed along with it, so that the documentation does not describe an exception the method no longer declares.

Declaring exceptions that are never thrown misleads callers into writing unnecessary error-handling code and obscures the method's true behavior.

org.openrewrite.staticanalysis.UnnecessaryThrows
mod run . --recipe=org.openrewrite.staticanalysis.UnnecessaryThrows

Install it once from Recipe actions, then run it on every repository under the current directory. New to the Moderne CLI? Set it up.