no-generic-exception

Try in Playground
python-best-practicesDesignError

0

No tags

No CWE or CVE

The specific error must be raised, not a generic Exception. Use the exact exception(s) you want to handle and have a recovery handler for each exception that your program may raise.

Ast Rule: try block


no-generic-exception

How to write a rule
function visit(node) {
  const genericExceptions = node.exceptClauses.flatMap(e => e.exceptions.filter(e => e.str === "Exception"));

  for (var i = 0 ; i < genericExceptions.length ; i++) {
    exception = genericExceptions[i];
    const error = buildError(exception.start.line, exception.start.col, exception.end.line, exception.end.col, "generic exception", "WARNING", "BEST_PRACTICES");
    addError(error);
  }
}

clear-exception.py

Expected test result: no error

a = 2
b = 0
try:
  c = a /b
except ValueError as e:
  pass

generic-exception.py

Expected test result: has error

a = 2
b = 0
try:
  c = a /b
except Exception as e:
  pass
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Explore
  • Cookbooks
  • Playground
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.