Programming & syntax · reviewed in July 2026
Exception handling
Exception handling is Python's mechanism (try/except) for reacting to runtime errors without the program crashing outright. Risky code is wrapped in a try block, and the except block catches and responds to whatever error type occurs.
try:
value = 10 / divisor
except ZeroDivisionError:
value = 0Frequently asked questions
What is an exception in Python?
It's an object Python automatically creates when an error occurs — like dividing by zero (ZeroDivisionError) or accessing a key that doesn't exist (KeyError) — which interrupts normal flow until something catches it.
Is it fine to catch every exception with a bare except:?
Generally not: it hides unexpected errors that would be better left to fail loudly. It's better to catch the specific exception type you actually expect to handle.
What is the finally block for?
For code that must run regardless of whether an exception occurred — like closing a file or a connection, guaranteeing the resource gets released.