Home › Interview Questions › Provide a sample Python script that demonstrates t…

Provide a sample Python script that demonstrates the use of try, except, else, and finally blocks, explaining how each block executes.

🟡 Medium Coding Fresher level
1Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

Here is a simple Python script that demonstrates the four parts of a try‑except block: try, except, else, and finally. The try block contains code that may raise an exception. The except block handles specific exceptions. The else block runs only if no exception was raised. The finally block runs regardless of whether an exception occurred, making it ideal for cleanup. In the example below, we divide two numbers. If the divisor is zero, a ZeroDivisionError is caught and a friendly message is printed. If the division succeeds, the result is printed in the else block. Finally, the finally block prints a message that always executes, even if an exception was raised. This pattern ensures that resources are released and that the program can continue or exit gracefully.

def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError as e:
        print('Cannot divide by zero:', e)
    else:
        print('Result is', result)
    finally:
        print('Execution finished.')

You can call divide(10, 0) to see the except block, or divide(10, 2) to see the else block. The finally block always runs, so you will see 'Execution finished.' in both cases.

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