Errors & Files — Cheat Sheet
Python A–Z · 4 topics. Download the PDF or the Instagram carousel and share it.
Cheat Sheet · AiCanCode.org
Errors & Files
Python A–Z4 topicsQuick revision reference
1
Exceptions — try/except/else/finally
Python handles failures with exceptions: catch specific types with except, run success-only code in else, guarantee cleanup in finally — and never write a bare except.
- ✓Catch specific exceptions; bare except: also swallows Ctrl+C — never use it
- ✓else runs only when the try block succeeded; finally always runs
- ✓EAFP (try/except) is idiomatic over pre-checking (LBYL)
- ✓ValueError = bad value, TypeError = wrong type — interviewers check you know the difference
try / except / else / finally — each part's job
def read_marks(path):
try:
f = open(path) # may raise FileNotFoundError
marks = [int(line) for line in f] # may raise ValueError
except FileNotFoundError:
print("file missing — using empty list")
return []
except ValueError as e:
print(f"bad number in file: {e}")
return []
else:
print(f"loaded {len(marks)} marks") # ONLY if no exception
return marks
finally:
try: f.close() # ALWAYS runs
except NameError: pass # open itself failed
# Hierarchy matters — order except blocks specific -> general:
# except ZeroDivisionError: ... (child of ArithmeticError)
# except ArithmeticError: ... (child of Exception)
# A bare 'except:' also catches KeyboardInterrupt/SystemExit — never use it.2
Raising, Custom Exceptions & Chaining
raise signals failure; custom exception classes give your domain a vocabulary; raise...from chains causes so tracebacks tell the whole story.
- ✓Define a base exception per domain; subclass for specific failures
- ✓raise NewError(...) from original preserves the causal chain in tracebacks
- ✓Bare raise inside except re-raises the active exception (log-and-propagate)
- ✓Inherit from Exception, not BaseException (that would break Ctrl+C)
A domain vocabulary for failures
class PaymentError(Exception):
"""Base for all payment failures."""
class CardDeclined(PaymentError):
def __init__(self, card_last4, reason):
super().__init__(f"card *{card_last4} declined: {reason}")
self.card_last4 = card_last4
self.reason = reason
class GatewayTimeout(PaymentError):
pass
def charge(card, amount):
if amount > 50_000:
raise CardDeclined(card[-4:], "limit exceeded")
return "ok"
try:
charge("4242424242424242", 99_999)
except CardDeclined as e:
print("specific:", e.reason) # handle precisely
except PaymentError:
print("some other payment issue") # catch-all for the domain3
Files & the with Statement
open() + with reads and writes files with guaranteed closing; iterate file objects line by line for constant-memory processing of files of any size.
- ✓Always with open(...) — guaranteed close on success AND exception
- ✓Iterate the file object for constant memory; read() only for small files
- ✓Mode "w" truncates at open; "a" appends; add encoding="utf-8" for text
- ✓write() adds no newline; print(..., file=f) does
with + line iteration — the only pattern you need
# students.txt: one "name,marks" per line
with open("students.txt", encoding="utf-8") as f:
for line in f: # streams — file can be 10 GB
name, marks = line.strip().split(",")
print(name, int(marks))
# file auto-closed here, even on exceptions
# Small files — grab it all
with open("config.txt", encoding="utf-8") as f:
text = f.read()
# Multiple files in one with
with open("in.txt") as src, open("out.txt", "w") as dst:
for line in src:
dst.write(line.upper())
# Without with (what NOT to do):
# f = open("x.txt"); data = f.read(); f.close()
# ^ an exception between open and close leaks the handle4
JSON, CSV & pathlib
json.load/dump round-trip Python dicts to the web's data format, csv handles tabular files safely, and pathlib replaces string paths with a clean object API.
- ✓json: loads/dumps for strings, load/dump for files; keys become strings, tuples become lists
- ✓Use csv module (DictReader/DictWriter) — never split(",") manually
- ✓pathlib.Path joins with /, globs, mkdirs, and read_text/write_text in one call
- ✓Always newline="" when opening CSV files (per the csv docs) and encoding="utf-8"
loads/dumps (strings) vs load/dump (files)
import json
profile = {"name": "Asha", "skills": ["python", "sql"], "cgpa": 8.7}
s = json.dumps(profile, indent=2) # dict -> pretty string
print(s)
back = json.loads(s) # string -> dict
print(back["skills"][0]) # python
with open("profile.json", "w") as f: # dict -> file
json.dump(profile, f, indent=2)
with open("profile.json") as f: # file -> dict
data = json.load(f)
# Gotchas
json.dumps({1: "a"}) # keys stringified: '{"1": "a"}'
json.dumps((1, 2)) # tuples become lists: '[1, 2]'
# json.dumps(datetime.now()) -> TypeError: use .isoformat() firstLearn this free with Aria, your AI tutor → AiCanCode.org/learn/python