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.