SKY-L004 · Logic and resilience
Try block too broad
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] selector[tool.skylos.gate] rules, lists and counts it. - Finding type
- advice
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
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 importedWhat Skylos leaves alone
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
- Runs with
--qualityon Python files and visits everytrystatement. Atrywhose handlers all re-raise the caught exception catches nothing and is skipped, unless itsfinallyleaves withreturn,breakorcontinue. - Treats a
tryas 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 areturnof names or literals comes after it. For a boundary, the line and branch checks below are skipped. - Reports HIGH when the
trybody holds more than threeif,fororwhilestatements, counted through nested blocks but not inside nested function bodies. - 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.
- Reports MEDIUM when the body contains another
trythat catches something and is itself broad (more than three branches, or more than 15 lines and operations). An innertryinside a loop (per-item error handling) or one that only catchesImportErroris not counted. - Every finding is on the
tryline. 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.
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 importedWhen 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 thetryor 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.