Python Try...Except

Handle errors gracefully.

✍️ 3 exercises + code challenge in this lesson

When an error occurs, Python raises an exception. You can handle it instead of crashing:

  • try: code that may fail
  • except ValueError: handle a specific error
  • except Exception as e: handle any error and inspect it
  • else: runs if no error happened
  • finally: always runs
  • raise throws an exception yourself

Key Takeaways: Python Try...Except

Mastering Python Try...Except helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python Try...Except Code Example

Python
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError as e:
        return f"Wrong types: {e}"
    else:
        return result
    finally:
        print(f"divide({a!r}, {b!r}) finished")

print(divide(10, 2))
print(divide(10, 0))
print(divide("10", 2))

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

try:
    set_age(-5)
except ValueError as e:
    print("Error:", e)
Free sign-in required · Google login available

Python Try...Except Practice Exercises

Check what you learned in “Python Try...Except”.

/ 3 solved
Fill in the blank

Handle the error.

try:
    x = 1 / 0
 ZeroDivisionError:
    print("Cannot divide by zero")
✓ Correct! Not quite. Try again.
Multiple choice

Which block runs whether or not an error happened?

✓ Correct! Not quite. Try again.
Code challenge

Try int("abc") and print "Not a number" when a ValueError happens.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services