try / except

Handle errors gracefully instead of crashing.

Syntaxtry: ... except ValueError: ...

When something goes wrong, Python raises an exception. If nothing handles it, the program stops. A try/except block lets you catch the error and respond.

The parts

  • try — the code that might fail.
  • except — runs if a matching error occurs.
  • else — runs if no error occurred.
  • finally — always runs, for cleanup.
Flow of a try except finally blocktry: risky codeerrorno errorexcept: handleelse: successfinally: cleanup
Either except or else runs, and finally always runs at the end.

Example

Example · python
def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return 'Cannot divide by zero'
    else:
        return result
    finally:
        print('Done')

print(safe_divide(10, 2))
print(safe_divide(10, 0))

# Output:
# Done
# 5.0
# Done
# Cannot divide by zero

When to use it

  • An API client wraps a network request in try/except to return a friendly message on timeout.
  • A file loader catches FileNotFoundError to prompt the user to provide a valid path.
  • A type-safe parser catches ValueError when int() fails on malformed user input.

More examples

Basic try/except

Catches a ZeroDivisionError and prints a user-friendly message instead of crashing.

Example · python
try:
    result = 10 / 0
except ZeroDivisionError:
    print('Cannot divide by zero')

# Output:
# Cannot divide by zero

Multiple except clauses

Handles two different exception types in separate except clauses for precise error messages.

Example · python
def parse_age(s):
    try:
        age = int(s)
        return 100 // age
    except ValueError:
        print('Not a valid number')
    except ZeroDivisionError:
        print('Age cannot be zero')

parse_age('abc')   # Not a valid number
parse_age('0')     # Age cannot be zero

try / except / else / finally

Shows the full try/except/else/finally structure: else runs on success, finally always runs.

Example · python
try:
    f = open('data.txt')
except FileNotFoundError:
    print('File missing')
else:
    content = f.read()
    print('Read', len(content), 'chars')
finally:
    print('Done (always runs)')

Discussion

  • Be the first to comment on this lesson.