Courseiva
Exceptions and File I/O →mediumMultiple Choice

PCAP Exceptions and File I/O Practice Question

A company runs a data processing pipeline that reads CSV files from a network drive. Occasionally, the network drive is unreachable causing FileNotFoundError. The current code uses a bare except clause that catches all exceptions, which also masks programming errors like NameError. The lead developer wants to implement a more robust exception handling strategy. The requirement is to log the specific error (including the filename) and retry the operation up to 3 times with a 2-second delay between retries. If after 3 attempts the file is still inaccessible, the pipeline should skip the file and continue with the next one. Which approach best meets these requirements?

⚠ Common exam trap

Python Institute often tests the distinction between catching OSError (specific to file/OS errors) versus Exception (which catches everything including NameError), and candidates mistakenly choose the broader catch because they think 'all exceptions' includes file errors, ignoring the requirement to not mask programming 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 OSError, with a retry loop that logs the error and continues after max retries.

It catches OSError, which is the parent class for file-related errors like FileNotFoundError, while still allowing programming errors like NameError to propagate. The retry loop with a 2-second delay and a maximum of 3 attempts satisfies the requirement, and after exhausting retries, the loop naturally continues to the next file, skipping the problematic one.

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 os.path.exists before opening the file, and if it returns False, log and skip.

    Why it's wrong here

    This look-before-you-leap (LBYL) approach is vulnerable to a time-of-check to time-of-use race condition: the file can be deleted, renamed, or lose permissions between the os.path.exists() call and the subsequent open(), which will then raise an exception that is never handled. Additionally, os.path.exists() only verifies path existence, not that the file is readable, holds a valid CSV, or that the underlying network share is responsive, so a false positive still leads to an unhandled failure. Even if the check returns False properly, logging and skipping the file silently means data can be dropped without any retry or alerting, which is unacceptable for a production data processing pipeline.

  • ✓

    Use a try-except block catching OSError, with a retry loop that logs the error and continues after max retries.

    Why this is correct

    This is the correct strategy because it follows the easier-to-ask-forgiveness-than-permission (EAFP) idiom and catches OSError exactly, which is the base class for I/O failures such as FileNotFoundError, PermissionError, and BrokenPipeError. The retry loop with a maximum retry count is essential for transient network-drive hiccups or brief file locks, while logging the specific error and the retry attempt gives operators visibility into what happened. After exhausting the retries, the loop logs the final failure and continues to the next file, ensuring the pipeline does not crash on a single bad input. This approach is precise, non-recursive, and aligns with best practices for robust file processing.

  • ✗

    Use a try-except block catching Exception, with a retry loop and logging.

    Why it's wrong here

    Catching the overly broad Exception class is dangerous because it will trap not only the intended file I/O errors but also programming mistakes like TypeError from malformed arguments, AttributeError from mis-typed variables, or ValueError from bad CSV data — none of which will be fixed by retrying. These bugs should fail fast so developers can detect and correct them, but wrapping them in a retry loop only masks them and makes the pipeline continue with corrupted or incomplete data. A retry loop is only justified for exceptions that are known to be transient, and Exception includes too many permanent, non-retryable conditions; the correct choice is to catch OSError specifically, which covers the realistic file-related failures.

  • ✗

    Use a with statement; if an exception occurs, call the function recursively up to 3 times.

    Why it's wrong here

    Recursive retry (calling the processing function upon exception) is a poor design because it forces the retry count to be controlled by recursion depth, and while a fixed depth of 3 is unlikely to hit Python's recursion limit, the approach is still needlessly complex and wastes stack frames on every retry. More importantly, recursion makes control flow harder to trace and test, and the retry counter must be threaded through the function signature or a closure, which is error-prone. A simple iterative loop (e.g., for attempt in range(max_retries)) is clearer, more memory efficient, and avoids any risk of recursion-related bugs; the with statement that follows has no bearing on whether retries are implemented as a loop or recursion.

Visual reference

192.168.1.0 /24 256 addresses (254 usable) 192.168.1.0 /25 Subnet A 128 addr (126 usable) 192.168.1.128 /25 Subnet B 128 addr (126 usable) Borrowing 1 bit from host portion creates 2 subnets (/25)

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 →

How Courseiva writes practice questions · Editorial policy

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.