Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do try, except, else and finally work together in Python?

SHORT ANSWER

try holds the risky code, except handles an error, else runs only if no exception occurred, and finally always runs, whether or not there was an error. Use else for code that depends on the try succeeding.

Explain it simply

Think of a UPI payment. You try to pay. If it fails, you handle the failure (except). If it succeeds, you show the success slip (else). Either way, you close the payment screen (finally).

Example

python
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("cannot divide by zero")
        return None
    else:
        print("division worked")
        return result
    finally:
        print("done")

print(divide(10, 2))
# Output: division worked
# Output: done
# Output: 5.0
print(divide(1, 0))
# Output: cannot divide by zero
# Output: done
# Output: None

Notice that finally printed before the return value was shown, even though return was already reached. It runs on the way out.

What to say in the interview

"try is the risky block, except catches specific exceptions, else runs only when nothing was raised, and finally always runs, so it's the place for cleanup like closing files. I keep the try block small and put the follow-up code in else, so an error there isn't accidentally caught by my except."

Common mistakes

  • Putting a lot of unrelated code in try, which hides real bugs.

#python#exceptions

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.