Python Cheatsheet

Exceptions

Use this Python reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Basic try / except

try:
    result = 10 / x
except ZeroDivisionError:
    result = 0

# Catch multiple exception types
except (TypeError, ValueError):
    pass

# Bind exception to variable
except ValueError as e:
    print(e)          # message
    print(repr(e))    # 'ValueError("invalid literal...")'
    print(type(e))    # <class 'ValueError'>
    print(e.args)     # tuple of arguments passed to exception

# Catch any exception (avoid unless re-raising)
except Exception as e:
    log(e)
    raise             # re-raise the same exception

# Full form
try:
    risky()
except ValueError as e:
    handle(e)
else:
    print("no exception")   # runs only if no exception was raised
finally:
    cleanup()               # always runs (even if return/break/continue)

Raising Exceptions

raise ValueError("invalid input")
raise TypeError(f"expected int, got {type(x)}")
raise RuntimeError("something went wrong") from original_exc  # chaining

# Re-raise current exception
except Exception:
    log_something()
    raise

# Suppress context (use sparingly)
raise RuntimeError("new") from None

# Raise arbitrary exception class
raise exc_class(message)

Exception Hierarchy

BaseException
 ├── SystemExit            # sys.exit()
 ├── KeyboardInterrupt     # Ctrl+C
 ├── GeneratorExit
 └── Exception             # base for all "normal" exceptions
      ├── ArithmeticError
      │    ├── ZeroDivisionError
      │    ├── OverflowError
      │    └── FloatingPointError
      ├── AttributeError
      ├── EOFError
      ├── ImportError
      │    └── ModuleNotFoundError
      ├── LookupError
      │    ├── IndexError
      │    └── KeyError
      ├── MemoryError
      ├── NameError
      │    └── UnboundLocalError
      ├── OSError (also IOError, EnvironmentError)
      │    ├── FileNotFoundError
      │    ├── FileExistsError
      │    ├── PermissionError
      │    ├── TimeoutError
      │    ├── ConnectionError
      │    │    ├── ConnectionRefusedError
      │    │    ├── ConnectionResetError
      │    │    └── ConnectionAbortedError
      │    └── IsADirectoryError
      ├── RuntimeError
      │    ├── RecursionError
      │    └── NotImplementedError
      ├── StopIteration
      ├── StopAsyncIteration
      ├── SyntaxError
      │    └── IndentationError
      ├── TypeError
      ├── ValueError
      │    └── UnicodeError
      │         ├── UnicodeDecodeError
      │         ├── UnicodeEncodeError
      │         └── UnicodeTranslateError
      └── Warning
           ├── DeprecationWarning
           ├── UserWarning
           ├── SyntaxWarning
           └── RuntimeWarning

Custom Exceptions

# Minimal custom exception
class AppError(Exception):
    pass

# With message
class ValidationError(Exception):
    def __init__(self, field, message):
        self.field = field
        self.message = message
        super().__init__(f"{field}: {message}")

raise ValidationError("email", "invalid format")

# Hierarchy
class AppError(Exception):         pass
class DatabaseError(AppError):     pass
class NetworkError(AppError):      pass
class AuthError(NetworkError):     pass

try:
    ...
except AppError as e:          # catches all app errors
    ...
except DatabaseError as e:     # catches only DB errors
    ...

Exception Chaining

# Explicit chaining — sets __cause__
try:
    open("missing.txt")
except FileNotFoundError as e:
    raise RuntimeError("Config failed to load") from e

# Implicit chaining — sets __context__ (happens automatically)
try:
    bad()
except TypeError:
    raise ValueError("wrong value")  # __context__ = TypeError instance

# Suppress chaining
raise RuntimeError("clean message") from None

# Inspect chain
try:
    ...
except RuntimeError as e:
    print(e.__cause__)    # explicitly chained
    print(e.__context__)  # implicitly chained

Exception Groups (Python 3.11+)

# Raise multiple exceptions at once
raise ExceptionGroup("multiple errors", [
    ValueError("bad value"),
    TypeError("wrong type"),
])

# Handle with except*
try:
    raise ExceptionGroup("errors", [ValueError("v"), TypeError("t")])
except* ValueError as eg:
    print("Value errors:", eg.exceptions)
except* TypeError as eg:
    print("Type errors:", eg.exceptions)

Warnings

import warnings

warnings.warn("deprecated", DeprecationWarning, stacklevel=2)
warnings.warn("use X instead", FutureWarning)

# Filter warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("error", category=RuntimeWarning)  # raise as error
warnings.filterwarnings("always")  # always show
warnings.resetwarnings()

# Temporarily suppress
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    noisy_function()

Context Managers for Exception Handling

from contextlib import suppress, contextmanager

# suppress — silently catch and ignore specific exceptions
with suppress(FileNotFoundError):
    os.remove("temp.txt")      # no error if file doesn't exist

# contextmanager — custom context that handles exceptions
@contextmanager
def managed_resource():
    resource = acquire()
    try:
        yield resource
    except SpecificError:
        handle_error()
    finally:
        release(resource)

with managed_resource() as r:
    use(r)

traceback Module

import traceback

try:
    bad()
except Exception as e:
    traceback.print_exc()                    # print to stderr
    traceback.print_exception(e)             # same, Python 3.10+
    s = traceback.format_exc()               # as string
    frames = traceback.extract_tb(e.__traceback__)  # FrameSummary list
    for frame in frames:
        print(frame.filename, frame.lineno, frame.name, frame.line)

# Print without catching
traceback.print_stack()        # current stack trace (no exception)

Best Practices

# 1. Be specific — catch the narrowest exception possible
except ValueError:       # good
except Exception:        # only if you re-raise or truly need it

# 2. Never silently swallow exceptions
except Exception:
    pass                 # BAD — hides bugs

except Exception as e:
    logger.error("unexpected error", exc_info=True)  # GOOD

# 3. Use finally for guaranteed cleanup (or use with)
f = open("file")
try:
    process(f)
finally:
    f.close()

# 4. Avoid using exceptions for flow control when possible
# (though catching StopIteration, LookupError for dict/list is fine)

# 5. Check OSError attributes
try:
    open("file")
except OSError as e:
    print(e.errno)       # error number (errno module)
    print(e.strerror)    # human-readable message
    print(e.filename)    # file that caused the error