What is the output of this Python code?
try: print("Start") x = 1 / 0 except ZeroDivisionError: print("Caught division by zero") finally: print("Finally block executed")
Remember that the finally block always runs, even if an exception occurs.
The code prints "Start" first. Then it tries to divide by zero, which raises ZeroDivisionError. The except block catches it and prints "Caught division by zero". Finally, the finally block runs and prints "Finally block executed".
What is the output of this Python code?
def func(): try: return 'try' except: return 'except' finally: return 'finally' print(func())
The finally block runs after return statements and can override the return value.
Even though the try block returns 'try', the finally block runs last and its return value 'finally' overrides the previous return.
Consider this code snippet. What will be printed?
def test(): try: raise ValueError('error') finally: print('In finally') try: test() except Exception as e: print(f'Caught: {e}')
The finally block runs before the exception is caught outside.
The function test raises a ValueError. Before the exception leaves test, the finally block prints 'In finally'. Then the exception is caught in the outer try-except and prints 'Caught: error'.
What happens when an exception is raised in the finally block?
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')
Exceptions in finally override previous exceptions.
The try block raises ValueError, which is caught and printed. The finally block runs and prints 'Finally block', but then raises RuntimeError. This new exception replaces the original one and is shown after the prints.
What is the output of this code and why?
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}')
The finally block runs after the except block but before the exception propagates.
The function prints 'A', then raises 'E1'. The except catches it, prints 'B', and raises 'E2'. Before 'E2' propagates, the finally block runs and prints 'C'. Outside, the try-except catches 'E2' and prints 'D: E2'.