Exceptions — try/except/else/finally — Concept Check
Questions on Exceptions — try/except/else/finally. Python handles failures with exceptions: catch specific types with except, run success-only code in else, guarantee cleanup in finally — and never write a bare except.
Questions in this quiz
8 questions on Exceptions — try/except/else/finally — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.A developer writes a function to open a file and read integers, but it sometimes crashes with a ValueError. What should they do to handle this exception properly?
- APre-check each line to ensure it's an integer before reading.
- BRemove the try block to see the full traceback.
- CAdd an except ValueError block to handle invalid integers.
- DUse a bare except to catch all exceptions.
2.A script reads from a dictionary and occasionally fails with a KeyError. What is the Pythonic way to handle this?
- AUse a bare except to catch all exceptions.
- BUse try/except to catch KeyError and handle it.
- CCheck if the key exists before accessing it.
- DWrap the access in a try block without an except.
3.What happens if a finally block contains code that raises an exception?
- AThe exception is ignored, and the program continues.
- BThe exception from finally replaces any previous exception.
- CThe exception is logged but not propagated.
- DThe program crashes immediately, ignoring finally.
4.A developer uses multiple except blocks in their code. Which order should they follow?
- APlace general exceptions before specific ones.
- BPlace specific exceptions before general ones.
- COrder does not matter for except blocks.
- DUse a bare except first for simplicity.
5.In a try/except/else/finally structure, when does the else block execute?
- AOnly if the try block raises an exception.
- BNever, if there is a finally block.
- COnly if the try block does not raise an exception.
- DAlways, after the try block.
6.A function attempts to close a file in a finally block but sometimes raises a NameError. Why might this happen?
- AThe file path is incorrect.
- Bfinally blocks cannot raise exceptions.
- CThe file was never opened due to an earlier exception.
- DThe file is already closed.
7.Why is it advised not to use a bare except in Python?
- AIt makes code run faster but less reliably.
- BIt catches too few exceptions.
- CIt catches all exceptions, including system-exiting ones.
- DIt only catches exceptions in the try block.
8.What is the professional guideline for handling exceptions in Python?
- ACatch only exceptions you can handle and let others propagate.
- BUse finally to handle exceptions.
- CCatch the broadest exception possible.
- DAvoid using try/except for cleaner code.