Skip to content
    Pythonia

    EXCEPTION HANDLING · 8 MIN

    Exception Handling

    try/except catches errors so a program can recover instead of crashing.

    PYRA explains

    • Put risky code in try; handle specific errors in except ValueError:, except ZeroDivisionError: …
    • else runs if no error happened; finally always runs — good for cleanup.
    • raise lets your own code signal a problem: raise ValueError("age must be positive").

    Real world: A car's airbag: you hope it's never needed, but it stops one problem becoming a disaster.

    Code

    def safe_div(a, b):
        try:
            return a / b
        except ZeroDivisionError:
            return "cannot divide by zero"
        finally:
            print("checked", a, b)
    print(safe_div(6, 3))
    print(safe_div(1, 0))
    Output ›
    checked 6 3
    2.0
    checked 1 0
    cannot divide by zero
    Try it in the online compiler →

    Checkpoint quiz

    Which block always runs, error or not?