Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect documented @throws for (checked) exceptions that are never thrown #610

Open
Luro02 opened this issue Oct 8, 2024 · 0 comments
Open
Labels
D-easy Easy to implement. enhancement New feature or request new-lint A new lint.

Comments

@Luro02
Copy link
Collaborator

Luro02 commented Oct 8, 2024

What it does

For example, one could have a javadoc like this one:

/**
 * Main entry point for the application.
 * 
 * @param args no arguments are expected
 * @throws InvalidArgumentException if something breaks
 */
public static void main(String[] args) {
    System.out.println("Hello World!");
}

where the mentioned InvalidArgumentException is a checked exception. Because it has a checked exception, it must be either caught in the method or the method must be annotated with an @throws.

The implementation for this should be easy:

  1. Visit every CtMethod
  2. Check if the method has a javadoc, if it does not, skip it.
  3. Keep track of all exceptions thrown by the method
  4. Parse the doc with the javadoc parser like here (create a utility method as well, so we don't have duplicate code)
    try {
    JavadocParser parser = new JavadocParser(ctJavaDoc.getRawContent(), ctJavaDoc.getParent());
    return parser.parse()
    .stream()
    .flatMap(element -> element.accept(new ReferenceFinder()).stream())
    .anyMatch(otherReference -> isReferencingTheSameElement(ctReference, otherReference));
    } catch (AssertionError e) {
    // the javadoc parser did throw an assertion error on javadoc that was not valid, but the code did compile,
    // so this is caught here to prevent the whole thing from crashing;
    //
    // The javadoc in question was: "/**\n * @param length the {@param string} and {@param value}.\n */"
    return false;
    }
  5. Then visit every @throws where one checks if it is a checked exception and if it is part of the throws for the method, if not, report a problem.

Lint Name

DOCUMENTED_EXCEPTION_NOT_THROWN

Category

comment

Example

See above.

@Luro02 Luro02 added enhancement New feature or request D-easy Easy to implement. new-lint A new lint. labels Oct 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
D-easy Easy to implement. enhancement New feature or request new-lint A new lint.
Projects
None yet
Development

No branches or pull requests

1 participant