Skip to main content

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.

L1

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 print the 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. Matching except handlers catch specific types.
  • Order handlers from specific to general.
  • Bind the instance with as e and print e (or str(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

  • else runs only when the try block did not raise.
  • finally always 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 raise inside except re-raises the current exception.
  • raise NewError("...") from e chains 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 (includes SystemExit, KeyboardInterrupt).
  • Exception → almost all errors you should catch in app code.
  • Catching bare except: or BaseException can swallow Ctrl+C — avoid.
TypeTypical causeCatch in apps?
ExceptionGeneral base for errorsYes, as a fallback
ValueErrorRight type, wrong valueYes
TypeErrorWrong type / arityYes
KeyError / IndexErrorMissing key / bad indexYes
FileNotFoundErrorPath missingYes
KeyboardInterruptCtrl+CRarely
SystemExitsys.exitNo (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.

Python exception hierarchy tree: object, BaseException with special SystemExit KeyboardInterrupt GeneratorExit, Exception branching into ArithmeticError LookupError OSError common errors ValueError TypeError and others like RuntimeError RecursionError StopIteration.
Python exception hierarchy — catch Exception families; avoid bare except: / BaseException
  • Special: SystemExit, KeyboardInterrupt, GeneratorExit — rarely catch.
  • Arithmetic / Lookup: ZeroDivisionError, IndexError, KeyError.
  • OS / I/O: FileNotFoundError, PermissionError under OSError.
  • Tip: child except blocks before parent; prefer except Exception over bare except:.

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)
L2

Advanced — Exception Handling

Exception chaining

  • raise X from e sets explicit cause; raise X from None hides 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, message raises AssertionError — 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 try blocks small so you know what failed.
L3

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.

L4

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)
L5

Problem Solving Tricks

  • Print Error:, e — never leave demo exceptions uncaught.
  • Order except clauses specific → general.
  • Use except (TypeA, TypeB) as e for shared handling.
  • Prefer custom exception types for domain logic branching.
  • finally is 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 from when wrapping library errors in your API.
  • Keep try blocks tight: one concern per try.
  • For files, prefer with open(...) over manual close in finally.
L6

Practice Programs List

  1. Catch ZeroDivisionError and ValueError in a mini calculator.
  2. Write InsufficientFundsError and use it in Account.withdraw.
  3. Demonstrate else and finally with a successful and failing path.
  4. Chain exceptions: wrap int() failures in ConfigError using raise from.
  5. Rewrite a LBYL dict check into EAFP try/except KeyError.
  6. Use contextlib.suppress for an optional file delete.
  7. Catch FileNotFoundError when opening a missing path; print e.
  8. Show why except Exception is safer than bare except (document it).
  9. Assert a non-empty list in a helper; catch AssertionError and print it.
  10. Build a function that tries several parsers and reports each Error message.