PCAP Exceptions and File I/O Practice Question
A developer writes a script that reads a configuration file. If the file does not exist, the program should print an error and continue. Which code snippet correctly implements this behavior?
⚠ Common exam trap
Python Institute often tests the distinction between catching a specific exception versus a broad or bare `except`, and the trap here is that candidates may think any `try-except` works, overlooking the requirement to catch only `FileNotFoundError` for precise error handling.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
try: open('config.txt') except FileNotFoundError: print('File not found')
It uses a `try` block to attempt opening the file and catches only `FileNotFoundError`, which is the specific exception raised when the file does not exist. This allows the program to print an error and continue execution without crashing, precisely matching the requirement.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✓
try: open('config.txt') except FileNotFoundError: print('File not found')
Why this is correct
This snippet is correct because it confines the error handling to exactly the condition the developer cares about: the file's absence. When the interpreter evaluates open('config.txt'), a missing config file raises a FileNotFoundError (a subclass of OSError), and that exception is caught and handled specifically. Other I/O problems, such as a permission denial or a path that is actually a directory, raise different OSError subclasses and are allowed to propagate, which preserves diagnostic accuracy.
- ✗
f = open('config.txt', 'r') if not f: print('File not found')
Why it's wrong here
The flaw in this option is its false premise about open()'s failure behavior. In Python, open() never returns None or False when it cannot find a file; it always raises an exception, specifically FileNotFoundError. If the file does not exist, the exception occurs on the first line and the script aborts before the if not f condition can ever be evaluated. Conversely, after a successful open(), the returned file object is always truthy, so the condition would never trigger even if the file existed.
- ✗
try: f = open('config.txt') except: print('File not found')
Why it's wrong here
Using a bare except: clause is an anti-pattern because it intercepts every exception type, including KeyboardInterrupt and SystemExit, which are BaseException subclasses rather than regular Exception subclasses. Although this code will successfully suppress FileNotFoundError, it will also silently hide memory errors and other critical conditions that a developer almost certainly wants to see. In addition, if the try block ever grows to contain more than just open(), the bare handler masks unrelated bugs, making the message 'File not found' misleading.
- ✗
try: with open('config.txt') as f: pass except Exception: print('File not found')
Why it's wrong here
This variant wraps the file access in a context manager, which is good for resource cleanup, but pairs it with an overly broad except Exception handler. Because FileNotFoundError is a subclass of Exception, the handler does catch the intended case, but it also catches any other Exception raised inside the with body or while exiting the manager. For example, if config-file parsing code in the with block later raises a ValueError or KeyError, the script will incorrectly print 'File not found', turning a genuine logic bug into a misleading diagnostic.
Go deeper
Related to this question
About these practice questions
Courseiva writes every PCAP question from scratch — 421 in total, each with an explanation and a wrong-answer breakdown. None are copied from real exams or dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This PCAP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCAP exam.