Home › Interview Questions › Explain the purpose and execution order of the try…

Explain the purpose and execution order of the try, except, else, and finally blocks in Python.

🟢 Easy Conceptual Junior level
1Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

Python's try/except/else/finally blocks allow you to handle exceptions gracefully and keep your code clean. The try block contains the code that might raise an exception. If an exception occurs, control jumps to the matching except block, where you can log the error, retry, or provide a fallback. If no exception is raised, the else block runs; this is useful for code that should only execute when the try block succeeds, such as committing a transaction. Finally, the finally block always executes, regardless of whether an exception was raised or not. It is typically used for cleanup actions like closing files, releasing locks, or disconnecting from a database. The execution order is: try → (except if an exception occurs) → else if no exception → finally. For example: try: result = 10 / 2 except ZeroDivisionError: print('Cannot divide by zero') else: print('Success') finally: print('Cleanup'). This structure ensures that resources are released and errors are handled predictably.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500