ArchUnit icon indicating copy to clipboard operation
ArchUnit copied to clipboard

Support for unchecked exceptions

Open breucode opened this issue 3 years ago • 5 comments

I would like to check, if a method throws an unchecked exception.

Currently, it seems, we can only check, if such Exceptions are instantiated, but there is no way, to look for a "throw" invocation.

breucode avatar Jun 13 '22 15:06 breucode

Yes, the actual throws statement is not supported yet, only throws declarations and catch clauses. I don't know how tricky it would be to add it :thinking: AFAIS it would involve overriding MethodProcessor.visitInsn(int opCode) and checking for org.objectweb.asm.Opcodes.ATHROW = 191. But the tricky part would likely be to find out which type of exception will actually be thrown, because that depends on the current stack :thinking: Maybe there is an easier way which I didn't find when looking into it quickly... I can't promise when I'll find the time to look into this, but if somebody else wants to give it a shot I'd be happy to add it!

codecholeric avatar Jun 16 '22 07:06 codecholeric

Hi there @codecholeric, I would like to dig into that issue, but I need some guidance :) Where I can find a code connected to throws statement is not supported yet, only throws declarations and catch clauses? Should the new logic resist in the same place?

mslowiak avatar Jul 14 '22 16:07 mslowiak

Hi @mslowiak, that's great! But just a warning, this might be a challenging issue :wink: (in other words, there are probably lower hanging fruits within the other open issues)

But if you're up for a challenge, the point to look into would be com.tngtech.archunit.core.importer.JavaClassProcessor. That is the place that hooks into the ASM API to parse the bytecode. The code for throws declarations is e.g. in com.tngtech.archunit.core.importer.JavaClassProcessor#visitMethod and the code for try-catch-blocks in com.tngtech.archunit.core.importer.JavaClassProcessor.MethodProcessor#visitTryCatchBlock. Let me know if you have any further questions!

codecholeric avatar Jul 14 '22 18:07 codecholeric

I have one more question regarding But the tricky part would likely be to find out which type of exception will actually be thrown, because that depends on the current stack.

Did you meant that if exception is thrown but then wrapped into some try catch then it shouldn't be counted as a violation of this rule? Or you had something different in mind?

mslowiak avatar Jul 21 '22 16:07 mslowiak

No, what I meant is that in the place where you see that an exception is thrown (MethodProcessor.visitInsn(int opCode)) you don't see which exception is actually thrown, but only that an ATHROW instruction is in the bytecode. So you need to figure out how to get the actual exception once you encounter this opcode.

codecholeric avatar Aug 20 '22 07:08 codecholeric