Skip to content

Module 12 · Exception Handling — topic 11 of 11

Best practices

Writing exception handling that helps rather than hides: catching specific errors, never silencing bugs, EAFP versus LBYL, cleaning up with with/finally, handling errors at the right level, and useful messages.

Beginner 10 min read·Lesson 193 of 306 in Python Programming

Learning objectives

  • Avoid the most damaging exception-handling mistakes
  • Choose between EAFP and LBYL
  • Decide where in a program errors should be handled

Definition

Exception-handling best practices are the habits that keep error handling precise, honest and maintainable: catch what you can handle, let the rest propagate, clean up reliably and report clearly.

Introduction

Bad exception handling is worse than none: a bare except: pass can hide a typo for months. A few habits keep error handling working for you.

Why it matters

Good handling makes failures obvious and recoverable; poor handling makes them invisible and expensive to debug.

Detailed explanation

Catch specific exceptions. except Exception or a bare except hides unrelated bugs such as NameError from typos.

Never silently swallow errors. If you deliberately ignore one, say so clearly — contextlib.suppress(FileNotFoundError) documents the intent.

EAFP ('easier to ask forgiveness than permission') tries the operation and handles failure; LBYL ('look before you leap') checks first. Python favours EAFP when failure is rare or checks would race, such as a file disappearing between the check and the open.

Handle errors where you can do something meaningful: retry, use a default, ask again, or report to the user. Low-level functions often should just raise; the program's boundary (main function, request handler) decides how to report.

Always release resources with with statements or finally.

Write messages that include the offending value and context, and chain translated errors with raise ... from.

Don't use exceptions for ordinary control flow when a simple if or dict.get is clearer.

Syntax

Python
from contextlib import suppress
with suppress(FileNotFoundError): # intentional ignore
os.remove("cache.tmp")
try:
value = data[key] # EAFP
except KeyError:
value = default
  • Specific types only.
  • Make intentional ignores explicit.
  • Handle errors where you can act.

Code examples

A bare except hides a bug

Python
def total_bad(items):
try:
return sum(item["price"] for item in itemz) # typo!
except:
return 0
def total_good(items):
try:
return sum(item["price"] for item in items)
except KeyError as e:
raise ValueError(f"item without {e}") from e
print(total_bad([{"price": 5}]))
print(total_good([{"price": 5}, {"price": 7}]))
Output
0
12

EAFP and LBYL

Python
data = {"a": 1}
# LBYL: check first
value = data["b"] if "b" in data else 0
# EAFP: try, then handle
try:
value2 = data["b"]
except KeyError:
value2 = 0
print(value, value2, data.get("b", 0))
Output
0 0 0

More examples

Intentional ignores and a safe boundary

Python
from contextlib import suppress
import os
with suppress(FileNotFoundError):
os.remove("definitely_missing_file.tmp")
print("missing file ignored on purpose")
def run_tasks(tasks):
results = {}
for name, func in tasks:
try:
results[name] = func()
except (ValueError, ZeroDivisionError) as e:
results[name] = f"failed: {e}"
return results
print(run_tasks([
("ratio", lambda: 10 / 4),
("parse", lambda: int("x1")),
("div", lambda: 1 / 0),
]))
Output
missing file ignored on purpose
{'ratio': 2.5, 'parse': "failed: invalid literal for int() with base 10: 'x1'", 'div': 'failed: division by zero'}

Step-by-step explanation

  • suppress makes it obvious that a missing file is expected and harmless.
  • run_tasks is a boundary: it records expected failures per task so one failure doesn't stop the others.
  • Unexpected exception types would still propagate, revealing real bugs.

Expected output

Running “Intentional ignores and a safe boundary” prints exactly:

TextOutput
missing file ignored on purpose
{'ratio': 2.5, 'parse': "failed: invalid literal for int() with base 10: 'x1'", 'div': 'failed: division by zero'}

Practical applications

  • Web frameworks convert uncaught exceptions into 500 responses and log them.
  • Batch jobs record failed items and continue.

Best practices

  • Catch specific exceptions and do something meaningful.
  • Let unexpected errors propagate to a boundary that logs them.
  • Clean up with with/finally and write helpful messages.

Common mistakes

except: pass

Avoid

try:
save(data)
except:
pass

Prefer

try:
save(data)
except OSError as e:
print(f"could not save: {e}")
raise

Silent failure means data loss nobody notices.

Exceptions for normal flow

Avoid

try:
count = counts[word]
except KeyError:
count = 0

Prefer

count = counts.get(word, 0)

A simple, expected case reads better with dict.get.

Important notes

  • The logging module's logger.exception() records the message and traceback inside an except block.

Key takeaways

  • Specific handlers, no silent failures.
  • Prefer EAFP when failure is rare or checks could race.
  • Handle errors where you can act; clean up reliably.

Try it yourself

  1. 1
    Review a piece of code with a bare except and rewrite it following these practices.
  2. 2
    Write a file-reading function using EAFP and another using LBYL; explain which is safer.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhy is a bare except: discouraged?
Practise this topic