4 ms·
I would value knowing how to flag the _lack_ of usage of the variable within the catch body; I had this problem while trying to write a semgrep rule for Java, b
by mdaniel 5y ago
I would value knowing how to flag the _lack_ of usage of the variable within the catch body; I had this problem while trying to write a semgrep rule for Java, but if I were working with python, it'd make me just as mad
I'll show the Java version first, because it's more obvious, then the equivalent in Python to stay moderately on-topic
try {
((String)null).length();
} catch (Exception e) {
System.err.println("I swallow errors for fun!");
}
try:
dict()["kaboom"]
except KeyError as ke:
logger.error("it did not work")
In the python version, I would accept the presence of `logger.exception` but my question in both code snippets is how to detect that nothing touches the exception variable within the catch block
- underyx 5y agoIf I understand the comment right, the solution is to first use pattern-inside to mark that you're interested in all try-except blocks, and then pattern-not-inside to remove the ones that correctly reraise the exception. Could you check this out? https://semgrep.dev/s/underyx:always-reraise https://semgrep.dev/s/underyx:always-reraise If this helped, I recommend joining https://r2c.dev/slack https://r2c.dev/slack — we've got a #rules channel dedicated to solving problems like this :)
- stavros 5y agoAs I understood it, the GP is looking to flag the non-usage of the "ke" variable in the exception body.
- whitten 5y agoWhy did the approach mentioned not work? 1) recognize all exception bodies. 2) recognize all exception bodies that use the ke variable and mark them as okay. Anything left should be an exception body that didn't use the ke variable, right ?
- stavros 5y agoIt sounds correct (as long as it can distinguish between use and shadowing), but the GP talked about reraising so I wasn't sure if they meant the same thing.