1. Home
  2. Interview Questions
  3. Python
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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 try block 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 the except clauses above.
  • finally: runs in every case. Use it for cleanup such as closing files, releasing locks or closing database connections.

The possible flows are:

SituationBlocks executed
No exceptiontry, else, finally
Exception matched by an excepttry (partly), except, finally
Exception not matchedtry (partly), finally, then the exception propagates
Exception raised inside except or elsefinally runs, then the new exception propagates

Two details interviewers like to probe:

  • finally runs even after return. If try or except executes return, the return value is computed first, then finally runs, 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 finally because 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 disappears

Common mistakes

  • Putting except Exception before except ValueError. The general clause matches first, so the specific one never runs.
  • Putting success-path code inside try instead of else. The except clause then catches errors you never meant to handle, which can hide real bugs.
  • Saying finally is skipped when the function returns early. It still runs.
  • Writing return inside finally. This silently swallows exceptions and overrides return values.

Follow-up questions

  • Why is the with statement often preferred over try/finally for closing files?
  • What happens if an exception is raised inside the finally block itself?
  • How do you catch several exception types in one except clause?

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

All easy questions →

Related Questions

‹
Q3 of 10 · Python
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA