Try-except-finally helps your program handle errors without crashing and always run important cleanup code.
Try–except–finally behavior in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
try: # code that might cause an error except SomeError: # code to handle the error finally: # code that always runs
The try block is where you put code that might fail.
The except block runs only if an error happens in try.
The finally block runs no matter what, even if there is an error or not.
Examples
Python
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") finally: print("This always runs.")
except is skipped but finally still runs.Python
try: print("Hello") except Exception: print("Error happened") finally: print("Done")
Sample Program
This program tries to divide by zero, catches the error, and always runs the final print. It shows how the flow moves through try, except, and finally.
Python
def test_try_except_finally(): try: print("Start") result = 10 / 0 print("This won't print") except ZeroDivisionError: print("Caught division by zero") finally: print("Always runs") print("End") test_try_except_finally()
Important Notes
If no error happens, the except block is skipped but finally still runs.
You can have multiple except blocks for different error types.
The finally block is useful for cleanup like closing files or releasing resources.
Summary
try runs code that might fail.
except runs only if an error happens.
finally always runs, no matter what.
Practice
1. What does the
finally block do in a try-except-finally structure?easy
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]
Hint: Remember: finally always runs last, no matter what. [OK]
Common Mistakes:
- Thinking finally runs only on errors
- Confusing except and finally blocks
- Believing finally runs before try
2. Which of the following is the correct syntax for a try-except-finally block in Python?
easy
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]
Hint: Remember order: try, except, then finally. [OK]
Common Mistakes:
- Placing finally before except
- Starting with except block
- Confusing else with finally
3. What will be the output of this code?
try:
print('Start')
x = 1 / 0
except ZeroDivisionError:
print('Error caught')
finally:
print('Always runs')medium
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]
Hint: finally always prints last, even after except. [OK]
Common Mistakes:
- Forgetting finally runs
- Assuming code stops after error
- Missing the initial print before error
4. Find the error in this code snippet:
try:
print('Hello')
except:
print('Error')
finally
print('Done')medium
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]
Hint: Check colons after try, except, finally lines. [OK]
Common Mistakes:
- Ignoring missing colon errors
- Confusing except and finally syntax
- Assuming indentation fixes missing colon
5. Consider this code:
def test():
try:
return 'try'
except:
return 'except'
finally:
return 'finally'
result = test()
print(result)
What will be printed?hard
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]
Hint: Return in finally overrides try/except returns. [OK]
Common Mistakes:
- Thinking try return is final
- Ignoring finally's return effect
- Assuming except runs without error
