- Home
- Interview Questions
- Python
- In what order do try, except, else and finally blocks run in…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: The try block runs first. If it raises, the first matching except block runs; if it does not raise, the else block runs. The finally block always runs last, whether an exception occurred, was handled, was not handled, or the code hit a return, break or continue.
Detailed explanation
A full exception-handling statement has four parts. Only try is mandatory, and it needs at least one except or a finally.
- try: the code that might fail. Keep it small so you only catch errors from the lines you expect to fail.
- except: Python checks the clauses from top to bottom and runs only the first one whose type matches the raised exception, including its parent classes. For this reason, specific exceptions must come before general ones like
Exception. - else: runs only if the
tryblock finished without raising. It is the right place for code that should run on success but whose own errors you do not want caught by theexceptclauses above. - finally: runs in every case. Use it for cleanup such as closing files, releasing locks or closing database connections.
The possible flows are:
| Situation | Blocks executed |
|---|---|
| No exception | try, else, finally |
| Exception matched by an except | try (partly), except, finally |
| Exception not matched | try (partly), finally, then the exception propagates |
| Exception raised inside except or else | finally runs, then the new exception propagates |
Two details interviewers like to probe:
- finally runs even after return. If
tryorexceptexecutesreturn, the return value is computed first, thenfinallyruns, then the function actually returns. - A return inside finally overrides everything. It replaces any earlier return value, and it silently discards an exception that was propagating. Newer Python versions emit a warning for return, break or continue inside
finallybecause this hides bugs.
finally also runs when sys.exit() is called, because that raises SystemExit. It does not run if the process is killed outright, for example with os._exit() or a hard crash.
Example
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print('cannot divide by zero')
return None
else:
print('division ok')
return result
finally:
print('cleanup runs')
divide(10, 2)
# division ok
# cleanup runs -> returns 5.0
divide(1, 0)
# cannot divide by zero
# cleanup runs -> returns None
def tricky():
try:
return 'from try'
finally:
return 'from finally'
print(tricky()) # from finally
def swallowed():
try:
raise ValueError('lost')
finally:
return 'no error seen'
print(swallowed()) # no error seen, the ValueError disappearsCommon mistakes
- Putting
except Exceptionbeforeexcept ValueError. The general clause matches first, so the specific one never runs. - Putting success-path code inside
tryinstead ofelse. Theexceptclause then catches errors you never meant to handle, which can hide real bugs. - Saying
finallyis skipped when the function returns early. It still runs. - Writing
returninsidefinally. This silently swallows exceptions and overrides return values.
Follow-up questions
- Why is the
withstatement often preferred overtry/finallyfor closing files? - What happens if an exception is raised inside the
finallyblock itself? - How do you catch several exception types in one
exceptclause?
Interview tip: Explain the order by walking through the two flows, success and failure, and then mention the return-in-finally trap. That detail shows you understand the mechanics and have not just memorised syntax.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More easy Python questions
Related Questions
- How do try, catch and finally work, and what happens if finally contains a return? · JavaScript · 1 ans
- What is exception chaining in Python and when should you use raise from? · Python · 1 ans
- How does the else clause work with for and while loops in Python? · Python · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- Why does using a mutable default argument like a list cause bugs in Python? · Python · 1 ans
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- What is broadcasting in NumPy and what rules decide whether two arrays can be combined? · Python · 1 ans
- Why does Pandas raise SettingWithCopyWarning and how do you fix chained assignment correctly? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)