Try–except–finally behavior in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time a program takes changes when using try, except, and finally blocks.
Specifically, we ask: how does adding error handling affect the number of steps the program runs?
Analyze the time complexity of the following code snippet.
def process(items):
for item in items:
try:
print(item / 2)
except TypeError:
print("Not a number")
finally:
print("Done with item")
This code goes through a list, tries to divide each item by 2, handles errors if the item is not a number, and always prints a message after each item.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for each item in the input list.
Each item causes a fixed number of steps: try dividing, maybe catch an error, then print a message.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 steps (3 steps per item) |
| 100 | About 300 steps |
| 1000 | About 3000 steps |
Pattern observation: The total steps grow directly with the number of items. Double the items, double the steps.
Time Complexity: O(n)
This means the time grows in a straight line with the number of items processed.
[X] Wrong: "Try-except-finally blocks make the program much slower and change how time grows with input size."
[OK] Correct: The error handling adds a small fixed cost per item, but the overall time still grows linearly with the number of items.
Understanding how error handling affects performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if the try block contained a nested loop over the items? How would the time complexity change?"
Practice
finally block do in a try-except-finally structure?Solution
Step 1: Understand the role of
Thetryandexcepttryblock runs code that might cause an error, andexceptruns only if an error happens.Step 2: Understand the
Thefinallyblock behaviorfinallyblock always runs aftertryandexcept, no matter if an error occurred or not.Final Answer:
It always runs, whether an error occurs or not. -> Option AQuick Check:
finallyalways runs = A [OK]
- Thinking finally runs only on errors
- Confusing except and finally blocks
- Believing finally runs before try
Solution
Step 1: Recall the order of blocks
The correct order istry, thenexcept, thenfinally.Step 2: Check each option's order
try: pass except: pass finally: pass follows the correct order. try: pass finally: pass except: pass placesfinallybeforeexcept, which is invalid. except: pass try: pass finally: pass starts withexcept, which is wrong. try: pass except: pass else: pass useselsebut nofinally.Final Answer:
try, except, finally in correct order -> Option CQuick Check:
try-except-finally order = C [OK]
- Placing finally before except
- Starting with except block
- Confusing else with finally
try:
print('Start')
x = 1 / 0
except ZeroDivisionError:
print('Error caught')
finally:
print('Always runs')Solution
Step 1: Trace the try block
The code prints 'Start' then tries to divide by zero, causing a ZeroDivisionError.Step 2: Handle the exception and finally block
The except block catches the error and prints 'Error caught'. Then the finally block runs and prints 'Always runs'.Final Answer:
Start\nError caught\nAlways runs -> Option DQuick Check:
try prints + except prints + finally prints = A [OK]
- Forgetting finally runs
- Assuming code stops after error
- Missing the initial print before error
try:
print('Hello')
except:
print('Error')
finally
print('Done')Solution
Step 1: Check syntax of try-except-finally
Each block header must end with a colon (:). Thefinallyline is missing a colon.Step 2: Verify other parts
Theexceptline has a colon, and indentation is correct.Final Answer:
Missing colon after finally -> Option BQuick Check:
Colon needed after finally = B [OK]
- Ignoring missing colon errors
- Confusing except and finally syntax
- Assuming indentation fixes missing colon
def test():
try:
return 'try'
except:
return 'except'
finally:
return 'finally'
result = test()
print(result)
What will be printed?Solution
Step 1: Understand return in try and finally
Thetryblock returns 'try', but thefinallyblock also has a return statement.Step 2: Know that finally return overrides others
In Python, iffinallyhas a return, it overrides any previous return from try or except.Step 3: Determine final output
The function returns 'finally', soprint(result)outputs 'finally'.Final Answer:
finally -> Option AQuick Check:
finally return overrides try/except returns = D [OK]
- Thinking try return is final
- Ignoring finally's return effect
- Assuming except runs without error
