finally-no-break-continue-return

Try in Playground
python-best-practicesDesignError

0

No tags

No CWE or CVE

When using return, break or continue in a finally block, it will stop the spread of any exceptions that were thrown in the try, else, or except blocks and will disregard any return statements.

Learn more in the official Python documentation.

Ast Rule: try block


finally-no-break-continue-return

How to write a rule
function visit(node, filename, code) {
  const flagElement = (element, typeToAvoid) => {
    const error = buildError(
      element.start.line, element.start.col,
      element.end.line, element.end.col,
      `do not use ${typeToAvoid} in finally block`, "ERROR", "BEST_PRACTICES");
    const edit = buildEditRemove(
      element.start.line, element.start.col,
      element.end.line, element.end.col);
    const fix = buildFix("remove statement", [edit]);
    addError(error.addFix(fix));
  }

  /**
   * Detect if there is a use of return, break or continue
   */
  const detectBreakOrContinue = (element) => {
    if (!element) {
      return;
    }

    if (element.astType === "sequence") {
      element.elements.forEach(e => detectBreakOrContinue(e));
    }

    if (element.astType === "break") {
      flagElement(element, "break");
    }

    if (element.astType === "continue") {
      flagElement(element, "continue");
    }
    if (element.astType === "return") {
      flagElement(element, "return");
    }
  };

  // trigger the rule if there is a finally clause only
  if (node.finallyClause) {
    const finallyClause = node.finallyClause;
    detectBreakOrContinue(finallyClause.content);
  }
}

error-return.py

Expected test result: no error

try:
		client_obj.get_url(url)
except (URLError, ValueError):
		client_obj.remove_url(url)
except SocketTimeout:
		client_obj.handle_url_timeout(url)
finally:
		return 0

error-continue.py

Expected test result: no error

try:
		client_obj.get_url(url)
except (URLError, ValueError):
		client_obj.remove_url(url)
except SocketTimeout:
		client_obj.handle_url_timeout(url)
finally:
		continue
Add comment

Log in to add a comment


    Be the first one to leave a comment!

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

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.