Full Structure

try:
    risky()
except ValueError as e:
    print("bad value:", e)
except (KeyError, IndexError):
    print("missing data")
else:
    print("ran with no error")
finally:
    print("cleanup")

Raising Exceptions

def set_age(age):
    if age < 0:
        raise ValueError("age cannot be negative")

Defining Custom Exceptions

class NotEnoughFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise NotEnoughFundsError(f"short by {amount - balance}")

Chaining Exceptions

try:
    int("x")
except ValueError as e:
    raise RuntimeError("invalid config") from e

Catching the Broad Exception — Carefully

try:
    run()
except Exception as e:
    logger.exception("unexpected failure")

Never use a bare except: — it swallows keyboard interrupts and system exits.

Practise this on PyForm — free

PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.

Open PyForm →