Skip to content

try/except in Python

Exceptions are normal in real programs:

  • network failures
  • missing files
  • invalid user input

Instead of crashing, you can handle the problem and continue.

basic_try_except.py
try:
    x = int(input("Enter a number: "))
    print(10 / x)
except Exception:
    print("Something went wrong")

This works, but it’s usually too broad.

specific_excepts.py
try:
    x = int(input("Enter a number: "))
    print(10 / x)
except ValueError:
    print("Please enter only digits.")
except ZeroDivisionError:
    print("Number can’t be 0.")
multi_except.py
try:
    x = int(input("Enter a number: "))
    print(10 / x)
except (ValueError, ZeroDivisionError) as e:
    print("Error:", e)
exception_object.py
try:
    int("abc")
except ValueError as e:
    print("Type:", type(e))
    print("Message:", e)
  • Catch the narrowest exception you can.
  • Don’t silently ignore exceptions.
  • Log exceptions in production systems.
  • Avoid except Exception: unless you re-raise or report clearly.

try / except / else / finally is a small decision tree. Python runs the try body; if an exception is raised it jumps to a matching except; the else runs only when no exception occurred; and finally always runs, error or not:

diagram try / except / else / finally mermaid
The except block runs only on an error, else only on success, and finally always runs.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading