Search code examples
archunit

Does exist a way to verify with ArchUnit that any method doesn´t throw any exception?


I would like to know if exist a way in ArchUnit to avoid that the signature of a method throws any checked exception.


Solution

  • You can access a code unit's declared exceptions via JavaMethod.getThrowsClause() (or JavaConstructor.getThrowsClause(), respectively).

    The following rule using a custom condition forbids the declaration of any exceptions – you can easily adapt it to your needs if you want to exclude RuntimeExceptions:

    @ArchTest
    static ArchRule no_code_units_should_declare_exceptions = noCodeUnits()
        .should(new ArchCondition<JavaCodeUnit>("declare exceptions") {
           @Override
           public void check(JavaCodeUnit codeUnit, ConditionEvents events) {
             int nThrowsDeclarations = codeUnit.getThrowsClause().size();
             String message = String.format("%s has %d throws declarations in %s",
                 codeUnit.getDescription(), nThrowsDeclarations, codeUnit.getSourceCodeLocation()
             );
             events.add(new SimpleConditionEvent(codeUnit, nThrowsDeclarations > 0, message));
           }
        });