📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Python from Zero Exception Handling

Exception Handling

5 min read Quiz at the end
Use try/except to handle errors gracefully. Catch specific exceptions like ValueError or FileNotFoundError. The finally block always runs for cleanup. Raise exceptions with raise and create custom ones with class.

Handling Exceptions

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (TypeError, ValueError):
    print("Wrong type or value")
else:
    print("No exception!")
finally:
    print("Always runs")

# Raise custom exception
raise ValueError("Bad input")
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which block handles exceptions?
💡 Python uses try/except — unlike Java/JavaScript which use try/catch.
2. Which block always runs?
💡 The finally block always runs, whether an exception occurred or not.
3. What does raise do?
💡 raise throws an exception: raise ValueError("message").
4. Which exception for wrong type?
💡 TypeError is raised when an operation is applied to wrong type.
5. What is the else block in try/except?
💡 The else block in try/except runs only if no exception was raised.