Advanced Python
Exception Handling
Complete lesson for Exception Handling using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Exception Handling
Section: Advanced Python. try / except / else / finally, raising errors, custom exceptions, and clean messages without scary tracebacks in demos.
Why exceptions?
- Exceptions signal unusual conditions without littering every call with status codes.
- EAFP — “Easier to Ask Forgiveness than Permission” — try the operation, catch failure.
- In tutorials and CLIs, catch errors and
printthe message; avoid dumping full tracebacks to beginners.
try:
print(10 / 0)
except ZeroDivisionError as e:
print("Error:", e) try / except anatomy
- Code that may fail goes in
try. Matchingexcepthandlers catch specific types. - Order handlers from specific to general.
- Bind the instance with
as eand printe(orstr(e)).
def parse_age(text: str) -> int:
return int(text)
try:
print(parse_age("21"))
print(parse_age("two"))
except ValueError as e:
print("Error:", e) Multiple except clauses
- Different failures need different messages or recovery.
- You can catch a tuple of types in one handler.
def lookup(data: dict, key: str, index: int):
return data[key][index]
try:
lookup({"nums": [1, 2]}, "nums", 5)
except KeyError as e:
print("Error:", e)
except IndexError as e:
print("Error:", e)
try:
lookup({"nums": [1, 2]}, "missing", 0)
except (KeyError, IndexError) as e:
print("Error:", e) else and finally
elseruns only when the try block did not raise.finallyalways runs — use for cleanup (closing files, releasing locks).
def divide(a: float, b: float) -> None:
try:
result = a / b
except ZeroDivisionError as e:
print("Error:", e)
else:
print("result=", result)
finally:
print("done")
try:
divide(8, 2)
divide(8, 0)
except Exception as e:
print("Error:", e) raise and re-raise
raise ValueError("msg")starts exception handling.- Bare
raiseinsideexceptre-raises the current exception. raise NewError("...") from echains causes (__cause__).
def positive(n: int) -> int:
if n <= 0:
raise ValueError("n must be positive")
return n
try:
print(positive(5))
print(positive(-1))
except ValueError as e:
print("Error:", e) Exception hierarchy (essentials)
BaseException→ top (includesSystemExit,KeyboardInterrupt).Exception→ almost all errors you should catch in app code.- Catching bare
except:orBaseExceptioncan swallow Ctrl+C — avoid.
| Type | Typical cause | Catch in apps? |
|---|---|---|
Exception | General base for errors | Yes, as a fallback |
ValueError | Right type, wrong value | Yes |
TypeError | Wrong type / arity | Yes |
KeyError / IndexError | Missing key / bad index | Yes |
FileNotFoundError | Path missing | Yes |
KeyboardInterrupt | Ctrl+C | Rarely |
SystemExit | sys.exit | No (let it exit) |
try:
raise FileNotFoundError("notes.txt not found")
except OSError as e: # FileNotFoundError is an OSError
print("Error:", e) Python exception hierarchy — BaseException to common errors
Everything that can be raised inherits from BaseException. Prefer catching
specific errors or Exception. Leave
SystemExit, KeyboardInterrupt, and GeneratorExit alone —
catching them can block exit or Ctrl+C.
Exception families; avoid bare except: / BaseException - Special:
SystemExit,KeyboardInterrupt,GeneratorExit— rarely catch. - Arithmetic / Lookup:
ZeroDivisionError,IndexError,KeyError. - OS / I/O:
FileNotFoundError,PermissionErrorunderOSError. - Tip: child
exceptblocks before parent; preferexcept Exceptionover bareexcept:.
Custom exceptions
- Subclass
Exception(or a more specific builtin) for domain errors. - Add attributes (e.g.
code) for programmatic handling.
class InsufficientFundsError(Exception):
def __init__(self, balance: float, amount: float) -> None:
self.balance = balance
self.amount = amount
super().__init__(f"need {amount}, have {balance}")
def withdraw(balance: float, amount: float) -> float:
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
try:
print(withdraw(1000, 200))
print(withdraw(1000, 1500))
except InsufficientFundsError as e:
print("Error:", e) EAFP vs LBYL
- LBYL — look before you leap: check conditions first (
if key in dict). - EAFP — try and catch (
data[key]inside try/except KeyError). - Python style prefers EAFP when races or clarity favour it; both are valid.
scores = {"Asha": 90}
# LBYL
if "Ravi" in scores:
print(scores["Ravi"])
else:
print("Error: missing Ravi")
# EAFP
try:
print(scores["Ravi"])
except KeyError as e:
print("Error:", e) Advanced — Exception Handling
Exception chaining
raise X from esets explicit cause;raise X from Nonehides the context.- When translating low-level errors to API errors, chaining preserves debug info for logs (print messages only for users).
def load_config(raw: str) -> int:
try:
return int(raw)
except ValueError as e:
raise ValueError("config must be an integer") from e
try:
load_config("abc")
except ValueError as e:
print("Error:", e)
if e.__cause__ is not None:
print("Cause:", e.__cause__) contextlib and cleanup
with open(...)guarantees close via the file’s context manager.contextlib.suppress(ExceptionType)ignores specific errors deliberately.
from contextlib import suppress
try:
with suppress(FileNotFoundError):
open("definitely-missing-pyv-oopa.txt", encoding="utf-8")
print("suppressed missing file")
except Exception as e:
print("Error:", e) Logging vs printing
- User-facing tools: print a short message.
- Services: log the traceback with
logging.exception(...)while returning a clean error to clients. - These lesson demos intentionally print
Error: …only.
Assertions
assert condition, messageraisesAssertionError— for internal invariants, not user input validation.- Assertions can be stripped with
python -O; do not rely on them for security checks.
def average(xs: list[float]) -> float:
assert xs, "empty list"
return sum(xs) / len(xs)
try:
print(average([2, 4]))
print(average([]))
except AssertionError as e:
print("Error:", e) Best practices
- Catch the narrowest exception you can handle.
- Never use bare
except:in application code. - Do not catch Exception just to ignore it — log or print, then continue only if safe.
- Keep
tryblocks small so you know what failed.
Tricky Interview Points
Q1) What is the difference between BaseException and Exception?
Answer BaseException is the root (includes SystemExit, KeyboardInterrupt). Exception is the subclass for almost all error conditions you should catch in programs.
Q2) Explain try/except/else/finally.
Answer try runs risky code; except handles matching errors; else runs if no exception; finally always runs for cleanup.
Q3) What is EAFP?
Answer Easier to Ask Forgiveness than Permission — attempt an operation and handle exceptions rather than pre-checking every condition.
Q4) How do you create a custom exception?
Answer Subclass Exception (or a finer builtin), optionally store fields, and raise it with a clear message.
Q5) What does raise ... from e do?
Answer Chains exceptions so the new error’s __cause__ points to e, preserving context for debugging.
Q6) Should you catch KeyboardInterrupt?
Answer Usually no — let it terminate the program. Catching BaseException can accidentally block Ctrl+C.
Q7) Bare except vs except Exception?
Answer Bare except catches BaseException too (including exit/interrupt). Prefer except Exception or a specific type.
Q8) When use assert?
Answer For developer invariants. Validate external/user input with explicit if/raise instead.
Q9) How does with help exception safety?
Answer Context managers run __exit__ even when an exception occurs, ensuring cleanup.
Q10) IndexError vs KeyError?
Answer IndexError: sequence index out of range. KeyError: missing mapping key.
Q11) What is finally useful for?
Answer Closing files, releasing locks, resetting state — runs whether or not an error occurred.
Q12) How do you print a friendly error without a traceback?
Answer Catch the exception as e and print a message like print("Error:", e) instead of letting it propagate uncaught.
Simple Programs
Safe division calculator
def safe_div(a: float, b: float) -> None:
try:
print(a / b)
except ZeroDivisionError as e:
print("Error:", e)
except TypeError as e:
print("Error:", e)
try:
safe_div(10, 2)
safe_div(10, 0)
safe_div(10, "2") # type: ignore[arg-type]
except Exception as e:
print("Error:", e) Read int with retries pattern
def read_int(values: list[str]) -> int | None:
for raw in values:
try:
return int(raw)
except ValueError as e:
print("Error:", e)
return None
try:
print(read_int(["x", "3.2", "42"]))
except Exception as e:
print("Error:", e) Bank withdraw custom error
class BankError(Exception):
pass
class InsufficientFundsError(BankError):
pass
class Account:
def __init__(self, balance: float) -> None:
self.balance = balance
def withdraw(self, amount: float) -> None:
if amount <= 0:
raise BankError("amount must be positive")
if amount > self.balance:
raise InsufficientFundsError("not enough balance")
self.balance -= amount
try:
acc = Account(500)
acc.withdraw(100)
print("balance", acc.balance)
acc.withdraw(1000)
except BankError as e:
print("Error:", e) else/finally demo
def load(path: str) -> None:
try:
data = open(path, encoding="utf-8").read()
except FileNotFoundError as e:
print("Error:", e)
else:
print("chars", len(data))
finally:
print("load attempt finished")
try:
load(__file__)
load("no-such-pyv-oopa-file.txt")
except Exception as e:
print("Error:", e) Translate errors with raise from
class ConfigError(Exception):
pass
def port_from(text: str) -> int:
try:
port = int(text)
except ValueError as e:
raise ConfigError("port must be an integer") from e
if not 1 <= port <= 65535:
raise ConfigError("port out of range")
return port
try:
print(port_from("8080"))
print(port_from("http"))
except ConfigError as e:
print("Error:", e) Dictionary access EAFP
def grade_for(roster: dict[str, str], name: str) -> None:
try:
print(name, "->", roster[name])
except KeyError as e:
print("Error:", e)
try:
grade_for({"Asha": "A"}, "Asha")
grade_for({"Asha": "A"}, "Ravi")
except Exception as e:
print("Error:", e) Problem Solving Tricks
- Print
Error:, e — never leave demo exceptions uncaught. - Order
exceptclauses specific → general. - Use
except (TypeA, TypeB) as efor shared handling. - Prefer custom exception types for domain logic branching.
finallyis for cleanup, not for handling logic.- Avoid bare
except:— it hides KeyboardInterrupt and bugs. - Validate user input with ValueError messages that state what was wrong.
raise fromwhen wrapping library errors in your API.- Keep try blocks tight: one concern per try.
- For files, prefer
with open(...)over manual close in finally.
Practice Programs List
- Catch ZeroDivisionError and ValueError in a mini calculator.
- Write InsufficientFundsError and use it in Account.withdraw.
- Demonstrate else and finally with a successful and failing path.
- Chain exceptions: wrap int() failures in ConfigError using raise from.
- Rewrite a LBYL dict check into EAFP try/except KeyError.
- Use contextlib.suppress for an optional file delete.
- Catch FileNotFoundError when opening a missing path; print e.
- Show why
except Exceptionis safer than bare except (document it). - Assert a non-empty list in a helper; catch AssertionError and print it.
- Build a function that tries several parsers and reports each Error message.