PCAP Exceptions and File I/O Practice Question
A data scientist writes a script to parse a configuration file that contains lines in 'key=value' format. Some lines may have malformed data that cause a ValueError when trying to convert the value to an integer. The requirement is to process all valid lines and skip any that cause a ValueError, but continue processing subsequent lines. The script should log a warning for each skipped line, including the line number. Which implementation correctly fulfills this requirement? (Assume the file is opened with 'with open(...) as f'.)
⚠ Common exam trap
Python Institute often tests the distinction between catching specific exceptions (ValueError) versus broad exceptions (Exception), and the trap here is that candidates may choose Option D thinking 'Exception' covers all errors, but it violates the principle of catching only what you can handle and may hide bugs.
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
✓
Inside a for loop over f, wrap the parsing in a try-except ValueError block, log the error, and continue.
It uses a try-except ValueError block inside the for loop, which catches the specific exception when converting the value to an integer, logs a warning with the line number, and continues to the next line. This ensures all valid lines are processed while malformed lines are skipped without halting execution, fulfilling the requirement exactly.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✓
Inside a for loop over f, wrap the parsing in a try-except ValueError block, log the error, and continue.
Why this is correct
Placing the try-except inside the for loop is the correct EAFP (Easier to Ask Forgiveness than Permission) pattern: each line is parsed individually, and a ValueError raised by int() (or float()) for a malformed literal is caught, logged, and skipped without terminating the loop. This preserves the required behavior of processing all remaining configuration lines, and catching the specific exception type avoids masking unrelated programming errors. The logging can include the offending line number via enumerate(f) to aid debugging.
- ✗
Wrap the entire file processing in a try-except ValueError block; if an error occurs, log and break.
Why it's wrong here
Wrapping the entire file processing in a single try-except ValueError block and breaking on the first error directly contradicts the requirement to continue parsing. Once a malformed line raises ValueError, the exception propagates out of the for loop and execution stops, so every subsequent valid line is never processed. It also loses the line-specific context unless the exception is somehow annotated, but the break itself is the fundamental flaw.
- ✗
Before parsing, check if the value string consists of digits using str.isdigit; if not, skip the line.
Why it's wrong here
Using str.isdigit() as a pre-check is a LBYL (Look Before You Leap) approach that fails for valid integer strings such as '-42' or '+42' because the leading sign is not a digit, and it also rejects valid numbers with surrounding whitespace (e.g., ' 42 '), which int() would parse normally. Furthermore, isdigit() returns True for some Unicode digits (like superscripts) that int() cannot convert, creating a validation mismatch. The robust approach is to attempt the conversion and catch ValueError.
- ✗
Inside a for loop over f, wrap the parsing in a try-except Exception block, log the error, and continue.
Why it's wrong here
Catching the broad Exception class inside the loop will indeed log and continue, but it is overly permissive and will swallow not only ValueError from int() but also unrelated bugs such as TypeError, AttributeError, or even NameError from typos in the parsing code. This makes the script difficult to debug because genuine logic errors are silently logged and skipped as if they were expected bad-line errors. The correct practice is to catch the specific ValueError, which represents the expected failure mode of int() on invalid input.
Go deeper
Related to this question
About these practice questions
One of 421 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 →
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.