Handling FileNotFoundError in Python
A developer writes a script to read a configuration file that may not exist. The script should handle the error gracefully and continue. Which approach is most Pythonic?
Quick Answer
The correct approach is to use a try-except block catching FileNotFoundError, as this directly handles the specific exception raised when a file does not exist. This is the most Pythonic method because it follows the EAFP (Easier to Ask for Forgiveness than Permission) principle, where you attempt the operation and gracefully handle the failure rather than checking conditions beforehand with cluttered if-statements. On the Certified Associate Python Programmer PCAP exam, this question tests your understanding of exception hierarchy and idiomatic error handling—a common trap is catching the overly broad Exception or OSError, which can mask unrelated bugs. Remember that FileNotFoundError is a subclass of OSError, so catching the specific type keeps your code precise and maintainable. A useful memory tip: think "EAFP first, LBYL last"—always prefer try-except for file operations over os.path.exists checks, as the file could be deleted between the check and the open call.
⚠ Common exam trap
Python Institute often tests the distinction between catching a specific exception (`FileNotFoundError`) versus a broader parent exception (`OSError`), and the trap here is that candidates may choose the broader catch thinking it is safer, without realizing it can mask other critical errors.
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
✓
Use a try-except block catching FileNotFoundError
It directly catches the specific `FileNotFoundError` exception, which is a subclass of `OSError` and is raised when a file does not exist. This approach follows the Pythonic principle of EAFP (Easier to Ask for Forgiveness than Permission), allowing the script to attempt the operation and handle the failure gracefully without redundant checks.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✓
Use a try-except block catching FileNotFoundError
Why this is correct
EAFP; clean and recommended for this scenario.
- ✗
Use a try-except block catching OSError
Why it's wrong here
Too broad; catches more than necessary.
- ✗
Use os.path.exists to check, then open if it exists
Why it's wrong here
LBYL approach; prone to race conditions and less Pythonic.
- ✗
Use an if statement to check file size
Why it's wrong here
Does not handle missing file; incorrect logic.
Go deeper
Related to this question
About these practice questions
One of 169 original PCAP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →
Same concept, more angles
3 more ways this is tested on PCAP
These questions test the same concept from different angles. Work through them to make sure you can recognise it however the exam phrases it.
Variation 1. 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?
easy- ✓ A.try: open('config.txt') except FileNotFoundError: print('File not found')
- B.f = open('config.txt', 'r') if not f: print('File not found')
- C.try: f = open('config.txt') except: print('File not found')
- D.try: with open('config.txt') as f: pass except Exception: print('File not found')
Why A: 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.
Variation 2. A developer writes a function that reads a configuration file and returns its contents as a string. The file might not exist. Which exception should be caught to handle a missing file?
easy- ✓ A.FileNotFoundError
- B.PermissionError
- C.IOError
- D.OSError
Why A: `FileNotFoundError` is a built-in exception in Python that is raised when a file or directory is requested but does not exist. In Python 3, file-related I/O errors are organized under `OSError` with specific subclasses, and `FileNotFoundError` is the precise exception for a missing file, making it the most appropriate catch for this scenario.
Variation 3. A developer writes a function that reads a file and processes its content. The function should handle the case where the file does not exist without catching other I/O errors. Which exception should be caught?
easy- A.PermissionError
- B.IOError
- C.OSError
- ✓ D.FileNotFoundError
Why D: `FileNotFoundError` is a specific subclass of `OSError` that is raised exactly when a file or directory is requested but does not exist. By catching only `FileNotFoundError`, the function handles the missing-file scenario without masking other I/O errors such as permission issues or disk failures, which is the precise requirement stated in the question.
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.