Skip to main content

SKY-L004 · Logic and resilience

Try block too broad

Varies

The catalog gives no severity. The detector reports HIGH for more than three if/for/while statements inside the try, MEDIUM for a broad nested try, and LOW for more than 15 lines of code.

A try block should wrap the one operation that can fail in the way the handler expects. When it wraps loops, branches and many statements, the handler also catches errors from code it was never meant to cover.

Languages
Python
Quality gate
counted toward the gate limits (full and diff scans). This is advice that the default report does not list ("measurement"), and unlisted advice is not counted. --all-advice, or naming the rule in [tool.skylos] select or [tool.skylos.gate] rules, lists and counts it.
Finding type
advice
Wrong result? Report itA false positive, a missed case or a confusing message: it goes privately to the founder.

Why it matters

In the example, a KeyError from a malformed row or a bug in add_line is not a database error, but anything the handler does catch rolls back the whole import and is logged as "order import failed". Wide catch scopes turn programming errors into misleading log lines.

What Skylos flags

orders/importer.py · PythonReported on line 12
import logging logger = logging.getLogger(__name__)  class DatabaseError(Exception):    pass  def import_orders(rows, db):    imported = []    try:        for row in rows:            if not row.get("sku"):                continue            if row["qty"] <= 0:                continue            order = db.find_order(row["id"])            if order is None:                order = db.create_order(row["id"])            order.add_line(row["sku"], row["qty"])            imported.append(order)        db.commit()    except DatabaseError:        db.rollback()        logger.exception("order import failed")    logger.info("imported %d orders", len(imported))    return imported

What Skylos leaves alone

orders/importer.py · Python
import logging logger = logging.getLogger(__name__)  class DatabaseError(Exception):    pass  def import_orders(rows, db):    """Import rows as orders; roll back everything on a database error."""    try:        imported = []        for row in rows:            if not row.get("sku"):                continue            if row["qty"] <= 0:                continue            order = db.find_order(row["id"])            if order is None:                order = db.create_order(row["id"])            order.add_line(row["sku"], row["qty"])            imported.append(order)        db.commit()        return imported    except DatabaseError:        db.rollback()        logger.exception("order import failed")        return []

Why Skylos leaves it alone

Here the try is the whole function after its docstring: it is the function's error boundary, an all-or-nothing import. Skylos does not measure the size or branching of such a try; that is the function's own size and complexity, which other rules report.

How Skylos decides

  1. Runs with --quality on Python files and visits every try statement. A try whose handlers all re-raise the caught exception catches nothing and is skipped, unless its finally leaves with return, break or continue.
  2. Treats a try as the function's error boundary when it is the last statement after only a docstring, imports, nested definitions and guard clauses, or when only literal or name assignments come before it and a return of names or literals comes after it. For a boundary, the line and branch checks below are skipped.
  3. Reports HIGH when the try body holds more than three if, for or while statements, counted through nested blocks but not inside nested function bodies.
  4. Reports LOW when the body has more than 15 lines of code and more than 15 operations. Blank lines, comments, string statements used as comments and the bodies of nested functions and lambdas are not counted, so one long call split over many lines does not trip it.
  5. Reports MEDIUM when the body contains another try that catches something and is itself broad (more than three branches, or more than 15 lines and operations). An inner try inside a loop (per-item error handling) or one that only catches ImportError is not counted.
  6. Every finding is on the try line. The rule is advice: the findings are in JSON output, but the terminal list shows them only with --all-advice.

How to fix it

Keep the row handling outside the try and wrap only db.commit(), the call that raises DatabaseError. A bad row now fails loudly instead of being reported as a database problem.

orders/importer.py · Python · the fix, against the flagged file
import logging logger = logging.getLogger(__name__)  class DatabaseError(Exception):    pass  def import_orders(rows, db):    imported = []Added:     for row in rows:Added:         if not row.get("sku"):Added:             continueAdded:         if row["qty"] <= 0:Added:             continueAdded:         order = db.find_order(row["id"])Added:         if order is None:Added:             order = db.create_order(row["id"])Added:         order.add_line(row["sku"], row["qty"])Added:         imported.append(order)    try:Removed:         for row in rows:Removed:             if not row.get("sku"):Removed:                 continueRemoved:             if row["qty"] <= 0:Removed:                 continueRemoved:             order = db.find_order(row["id"])Removed:             if order is None:Removed:                 order = db.create_order(row["id"])Removed:             order.add_line(row["sku"], row["qty"])Removed:             imported.append(order)        db.commit()    except DatabaseError:        db.rollback()        logger.exception("order import failed")Added:         return []    logger.info("imported %d orders", len(imported))    return imported

When it can be wrong

  • A transaction that must succeed or fail as a whole, with work after the try (a log line, a metric), is not recognised as a boundary and is reported. Moving that work into the try or a caller, or a suppression, is the answer.
  • The thresholds (15 lines, three branches) are fixed; there is no setting for them.

Seeing a case that isn't listed here? Report the wrong result so the rule can be fixed. Don't paste company code: describe the shape of it.

How to silence it

  • Put the marker on the try: line.

    Python
    try:  # skylos: ignore[SKY-L004] all-or-nothing import
  • [tool.skylos] ignore = ["SKY-L004"] turns the rule off for the project.

From the Skylos rule handbook, Skylos 5.8.0 (commit 5b880b0). All rules.