Bird
Raised Fist0
Pythonprogramming~20 mins

Try–except–finally behavior in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Try-Except-Finally Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of try-except-finally with exception

What is the output of this Python code?

Python
try:
    print("Start")
    x = 1 / 0
except ZeroDivisionError:
    print("Caught division by zero")
finally:
    print("Finally block executed")
AStart\nFinally block executed
BCaught division by zero\nFinally block executed
CStart\nCaught division by zero\nFinally block executed
DStart\nCaught division by zero
Attempts:
2 left
💡 Hint

Remember that the finally block always runs, even if an exception occurs.

Predict Output
intermediate
2:00remaining
Return value with try-except-finally

What is the output of this Python code?

Python
def func():
    try:
        return 'try'
    except:
        return 'except'
    finally:
        return 'finally'

print(func())
Afinally
Bexcept
CNone
Dtry
Attempts:
2 left
💡 Hint

The finally block runs after return statements and can override the return value.

🧠 Conceptual
advanced
2:00remaining
Exception propagation with finally

Consider this code snippet. What will be printed?

Python
def test():
    try:
        raise ValueError('error')
    finally:
        print('In finally')

try:
    test()
except Exception as e:
    print(f'Caught: {e}')
AIn finally\nCaught: error
BCaught: error\nIn finally
CIn finally
DCaught: error
Attempts:
2 left
💡 Hint

The finally block runs before the exception is caught outside.

Predict Output
advanced
2:00remaining
Exception in finally block

What happens when an exception is raised in the finally block?

Python
try:
    print('Try block')
    raise ValueError('Original error')
except ValueError as e:
    print(f'Caught: {e}')
finally:
    print('Finally block')
    raise RuntimeError('Error in finally')
ATry block\nFinally block\nCaught: Original error
BTry block\nCaught: Original error\nFinally block
CTry block\nCaught: Original error
DTry block\nCaught: Original error\nFinally block\nRuntimeError: Error in finally
Attempts:
2 left
💡 Hint

Exceptions in finally override previous exceptions.

🔧 Debug
expert
3:00remaining
Identify the output and explain the flow

What is the output of this code and why?

Python
def f():
    try:
        print('A')
        raise Exception('E1')
    except Exception as e:
        print('B')
        raise Exception('E2')
    finally:
        print('C')

try:
    f()
except Exception as e:
    print(f'D: {e}')
AA\nB\nD: E2\nC
BA\nB\nC\nD: E2
CA\nC\nB\nD: E2
DA\nC\nD: E1
Attempts:
2 left
💡 Hint

The finally block runs after the except block but before the exception propagates.

Practice

(1/5)
1. What does the finally block do in a try-except-finally structure?
easy
A. It always runs, whether an error occurs or not.
B. It runs only if an error occurs.
C. It runs only if no error occurs.
D. It runs before the try block.

Solution

  1. Step 1: Understand the role of try and except

    The try block runs code that might cause an error, and except runs only if an error happens.
  2. Step 2: Understand the finally block behavior

    The finally block always runs after try and except, no matter if an error occurred or not.
  3. Final Answer:

    It always runs, whether an error occurs or not. -> Option A
  4. Quick Check:

    finally always 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
A. except: pass try: pass finally: pass
B. try: pass finally: pass except: pass
C. try: pass except: pass finally: pass
D. try: pass except: pass else: pass

Solution

  1. Step 1: Recall the order of blocks

    The correct order is try, then except, then finally.
  2. Step 2: Check each option's order

    try: pass except: pass finally: pass follows the correct order. try: pass finally: pass except: pass places finally before except, which is invalid. except: pass try: pass finally: pass starts with except, which is wrong. try: pass except: pass else: pass uses else but no finally.
  3. Final Answer:

    try, except, finally in correct order -> Option C
  4. Quick 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
A. Start\nAlways runs
B. Start\nError caught
C. Error caught\nAlways runs
D. Start\nError caught\nAlways runs

Solution

  1. Step 1: Trace the try block

    The code prints 'Start' then tries to divide by zero, causing a ZeroDivisionError.
  2. 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'.
  3. Final Answer:

    Start\nError caught\nAlways runs -> Option D
  4. Quick 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
A. Missing colon after except
B. Missing colon after finally
C. Indentation error in try block
D. No error, code is correct

Solution

  1. Step 1: Check syntax of try-except-finally

    Each block header must end with a colon (:). The finally line is missing a colon.
  2. Step 2: Verify other parts

    The except line has a colon, and indentation is correct.
  3. Final Answer:

    Missing colon after finally -> Option B
  4. Quick 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
A. finally
B. except
C. None
D. try

Solution

  1. Step 1: Understand return in try and finally

    The try block returns 'try', but the finally block also has a return statement.
  2. Step 2: Know that finally return overrides others

    In Python, if finally has a return, it overrides any previous return from try or except.
  3. Step 3: Determine final output

    The function returns 'finally', so print(result) outputs 'finally'.
  4. Final Answer:

    finally -> Option A
  5. Quick 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