█
LastWrite
  • > Curriculum
  • > Pricing
  • > For Educators
  • > About
  • > Contact
Log InGet Started

Questions, concerns, bug reports, or suggestions? We read every message, write to us at [email protected].

More ways to reach us →
LastWrite

Structured computer science lessons for aspiring developers and security professionals.

[email protected]

(201) 785-7951

Mon–Fri, 9 AM–5 PM EST

Learn

  • Curriculum
  • Pricing

Company

  • About
  • For Educators & Schools
  • Contact Us

Legal

  • Terms of Service
  • Privacy Policy
© 2026 LastWrite. All rights reserved.
Curriculum/Programming Languages/Python (Professional)/Error Handling and Logging
40 minIntermediate

Error Handling and Logging

After this lesson, you will be able to: Use exceptions correctly, define custom exceptions, write context managers for cleanup, and log instead of print.

Error handling separates code that breaks loudly from code that breaks silently. The latter is worse.

Prerequisites:Pythonic Code

Exception handling done right

Catch specific, raise specific, never silence.

python
# Specific catches
try:
user = User.load(user_id)
except FileNotFoundError:
return None
except PermissionError:
log.error("perm denied")
raise
# Custom exception (informative type beats string parsing)
class UserNotFound(Exception):
def __init__(self, user_id: str):
super().__init__(f"user {user_id} not found")
self.user_id = user_id
# Try/finally vs context manager
try:
f = open("file")
data = f.read()
finally:
f.close()
# Better
with open("file") as f:
data = f.read()
# raise from (preserve traceback)
try:
parse(payload)
except ValueError as e:
raise InvalidPayload(payload) from e

Logging vs print

print() is fine for scripts. For anything else, use logging. logging gives you: levels (DEBUG/INFO/WARNING/ERROR/CRITICAL), structured output, file/syslog routing, on-by-default. Pattern: `log = logging.getLogger(__name__)` at module top; `log.info("...")` everywhere.

Logging setup

Drop in main entry point.

python
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
log = logging.getLogger(__name__)
log.info("app started")
log.warning("low disk")
log.exception("crash") # logs message + traceback automatically inside except

Common mistakes only experienced Python devs avoid

`except:` or `except Exception:` without re-raising. Swallows real bugs. Catching exceptions to print + return None. The caller has no idea what failed. Using print for ops logs. Lost on restart; no levels; no routing. Forgetting `from` clause when re-raising, original cause is gone.

Quick Check

What's wrong with `try: ... except: pass`?

Pick the cleanest answer.

Sign in and purchase access to unlock this lesson.

Sign in to purchase
←Pythonic Code
Back to Python (Professional)
File I/O and Working with Data→