Try–except–else 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 it takes to run a try-except-else block changes as the input changes.
Specifically, we ask: how often does the code inside each part run as input grows?
Analyze the time complexity of the following code snippet.
def process_items(items):
for item in items:
try:
result = 10 / item
except ZeroDivisionError:
result = 0
else:
result += 1
return result
This code tries to divide 10 by each item, handles division by zero, and adds 1 if no error occurs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs once for each item in the list.
- How many times: Exactly as many times as there are items (n times).
Each item causes one try-except-else check, so work grows directly with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 try-except-else checks |
| 100 | About 100 try-except-else checks |
| 1000 | About 1000 try-except-else checks |
Pattern observation: The total work grows in a straight line as input grows.
Time Complexity: O(n)
This means the time to run grows directly in proportion to how many items we process.
[X] Wrong: "The except block makes the code slower for all items, so time grows faster than input size."
[OK] Correct: The except block only runs when an error happens, so most items just run the try and else parts once each. The overall time still grows linearly.
Understanding how try-except-else affects time helps you explain error handling costs clearly and confidently in real coding situations.
"What if the except block contained a loop over all items? How would the time complexity change?"
Practice
else block do in a try-except-else structure?Solution
Step 1: Understand try-except-else flow
Thetryblock runs code that might cause an error. If an error happens, theexceptblock runs.Step 2: Role of else block
Theelseblock runs only if no error occurs in thetryblock, meaning the code succeeded without exceptions.Final Answer:
Runs only if no error occurs in the try block -> Option AQuick Check:
else runs if no error = A [OK]
- Thinking else runs after except
- Assuming else runs always
- Confusing else with finally
Solution
Step 1: Recall correct order of blocks
The correct order istry, thenexcept, thenelse. Theelseblock must come afterexcept.Step 2: Check each option
try: pass except: pass else: pass follows the correct order and syntax. Options A, B, and D have wrong order or misplaced blocks.Final Answer:
try: pass except: pass else: pass -> Option CQuick Check:
try-except-else order = C [OK]
- Placing else before except
- Using else after finally
- Starting with except block
try:
print("Start")
x = 1 / 1
except ZeroDivisionError:
print("Error")
else:
print("No Error")
print("End")Solution
Step 1: Analyze try block execution
The code prints "Start" and calculates 1/1 which is 1, no error occurs.Step 2: Determine which blocks run
Since no error,exceptblock is skipped,elseblock runs printing "No Error", then "End" prints after.Final Answer:
Start No Error End -> Option AQuick Check:
No error means else runs = D [OK]
- Thinking except runs without error
- Ignoring else block output
- Missing that print("End") always runs
try:
print(10 / 0)
else:
print("No error")
except ZeroDivisionError:
print("Error occurred")Solution
Step 1: Check block order in try-except-else
The correct order is try, except, then else. Here, else comes before except which is invalid syntax.Step 2: Confirm syntax error
Python raises a syntax error because else must follow except, not precede it.Final Answer:
else block is before except block -> Option DQuick Check:
else must come after except = A [OK]
- Placing else before except
- Forgetting except block
- Misordering try-except-else blocks
def check_value(val):
try:
result = 10 / val
except ZeroDivisionError:
return "Cannot divide by zero"
else:
return f"Result is {result}"
print(check_value(0))
print(check_value(5))
What is the output?Solution
Step 1: Analyze call with 0
When val=0, division causes ZeroDivisionError, so except block returns "Cannot divide by zero".Step 2: Analyze call with 5
When val=5, division succeeds (10/5=2.0), so else block returns "Result is 2.0".Final Answer:
Cannot divide by zero Result is 2.0 -> Option BQuick Check:
ZeroDivision triggers except, else runs if no error = B [OK]
- Assuming else runs even if error occurs
- Confusing output order
- Expecting runtime error instead of handled exception
