You are a junior developer at a logistics company. Your team maintains a Python script that processes daily shipment data from a CSV file. The script reads the file, computes total weight per shipment, and writes results to a new CSV. Recently, the script started crashing sporadically with a 'ValueError: invalid literal for int() with base 10: 'NULL''. The CSV file sometimes contains the string 'NULL' in the weight column for missing values. The current code reads the weight column as: weight = int(row['weight']). Your team lead wants a robust fix that handles missing data gracefully without crashing, and also logs the line number for any problematic rows for later review. Which of the following approaches best meets these requirements?
Catching ValueError around int() lets the script substitute a default weight for 'NULL' entries and continue processing, while a counter tracks the offending line for later review. This satisfies both the graceful-handling and line-logging constraints without halting the whole run.
Why this answer
It uses a try-except block to catch the ValueError when int() fails on 'NULL', sets weight to 0 as a fallback, and logs the line number using a counter variable. This approach handles any unexpected non-numeric string (not just 'NULL'), making it robust against future data anomalies, and satisfies the requirement to log problematic rows for review.
Exam trap
The PCEP exam often tests the distinction between LBYL (Look Before You Leap) and EAFP (Easier to Ask for Forgiveness than Permission) paradigms, and the trap here is that candidates choose a seemingly simple string check (like Option D) without realizing it fails for any unexpected invalid input, while the try-except approach is the recommended Pythonic solution for robust error handling.
How to eliminate wrong answers
Option A is wrong because .isdigit() returns False for negative numbers, floats, and empty strings, and it does not log the line number, failing the logging requirement. Option B is wrong because reading the entire file into a list and using a list comprehension without logging ignores the requirement to log line numbers for problematic rows, and it assumes all non-'NULL' values are valid integers, which is not guaranteed. Option D is wrong because it only checks for the literal string 'NULL', missing other invalid literals like empty strings or 'N/A', and while it logs a warning, it does not use a counter variable to log the specific line number as required.