0
0
Pythonprogramming~20 mins

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

Choose your learning style9 modes available
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.