All lessons
🛡️

Try / Except

Handle errors gracefully

Reward
+50 XP

Basic try/except

Wrap code that might fail in try, and handle the error in except.

try:
    x = int("hello")
except ValueError:
    print("Not a valid number!")

finally

The finally block runs no matter what — even if an exception occurred.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Can't divide by zero!")
finally:
    print("Done")

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • Catching too broad exceptions with bare except: — always specify the type.
  • Using try/except to hide bugs instead of fixing them.