Skip to content

try/except in Python

Why use try/except?

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

basic_try_except.py
try:
    x = int(input("Enter a number: "))
    print(10 / x)
except Exception:
    print("Something went wrong")
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.

Catch specific exceptions

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.")
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.")

Catch multiple exception types

multi_except.py
try:
    x = int(input("Enter a number: "))
    print(10 / x)
except (ValueError, ZeroDivisionError) as e:
    print("Error:", e)
multi_except.py
try:
    x = int(input("Enter a number: "))
    print(10 / x)
except (ValueError, ZeroDivisionError) as e:
    print("Error:", e)

Capture the exception object

exception_object.py
try:
    int("abc")
except ValueError as e:
    print("Type:", type(e))
    print("Message:", e)
exception_object.py
try:
    int("abc")
except ValueError as e:
    print("Type:", type(e))
    print("Message:", e)

Best practices

  • Catch the narrowest exception you can.
  • Don’t silently ignore exceptions.
  • Log exceptions in production systems.
  • Avoid except Exception:except Exception: unless you re-raise or report clearly.

πŸ§ͺ Try It Yourself

Exercise 1 – Catch a ValueError

Exercise 2 – Multiple Except Blocks

Exercise 3 – Raise a Custom Exception

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did