If no exception happens, Python skips the except blocks.
except block(s)
Handle specific exceptions.
You can have multiple except clauses to catch different error types.
The exception object (as e) contains details about what went wrong.
else block
Runs only if no exception was raised in the try block.
Useful for code that should execute only when the try succeeded.
finally block
Runs always, whether an exception occurred or not.
Commonly used for cleanup (closing files, releasing resources, etc.).
Your Example
try:
x = 1 / 0
except ZeroDivisionError as e:
print("Error:", e) # runs because division by zero happens
else:
print("No error") # skipped because an exception occurred
finally:
print("Always runs") # always executes
Output:
Error: division by zero
Always runs
More Examples
Multiple except clauses:
try:
num = int("abc")
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Division by zero")
Catching all exceptions (not always recommended):
try:
risky_operation()
except Exception as e:
print("Something went wrong:", e)
So in short:
try → attempt risky code
except → handle specific errors
else → runs only if no error
finally → always runs (cleanup)
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Exception Handling Flow
tryblockexceptblocks.exceptblock(s)exceptclauses to catch different error types.as e) contains details about what went wrong.elseblocktryblock.trysucceeded.finallyblockYour Example
Output:
More Examples
Multiple
exceptclauses:Catching all exceptions (not always recommended):
So in short:
try→ attempt risky codeexcept→ handle specific errorselse→ runs only if no errorfinally→ always runs (cleanup)