Courseiva
Exceptions and File I/OhardMultiple ChoiceObjective-mapped

File I/O Exception Handling in Python — Avoiding Resource Leaks

Consider the code fragment: f = open('data.txt', 'r') data = f.read() process_data(data) f.close() What is the primary risk if an exception occurs during process_data(data)?

Quick Answer

The correct answer is that the file descriptor may be leaked because the close() call is skipped. This happens because when process_data(data) raises an exception, execution jumps immediately to the nearest exception handler, bypassing the f.close() statement entirely. The technical concept here is resource leak: the open file handle remains allocated in memory, consuming a system file descriptor that cannot be reused until the program ends or garbage collection intervenes. On the PCAP exam, this scenario tests your understanding of file I/O exception handling and the dangers of manual resource management—a common trap is assuming close() will always run, when in fact any unhandled exception breaks that flow. The examiners want you to recognize that Python’s with statement is the safe alternative, as it guarantees cleanup via context manager protocols. Memory tip: think of a try block without a finally as a door left open—if an exception crashes the party, nobody shuts the door behind them.

⚠ Common exam trap

Python Institute often tests the misconception that Python's garbage collector immediately closes files, when in reality it only closes them during an unpredictable collection cycle, making explicit cleanup essential.

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

The file descriptor may be leaked because the close() call is skipped.

If `process_data(data)` raises an exception, the `f.close()` statement is never executed, leaving the file descriptor open. This is a resource leak that can exhaust system file handles, especially in long-running applications. Python's `with` statement is the recommended approach to guarantee automatic cleanup even when exceptions occur.

Answer analysis

Option-by-option breakdown

For each option: why learners choose it and why it is or isn't the right answer here.

  • The file descriptor may be leaked because the close() call is skipped.

    Why this is correct

    Correct: if an exception occurs, close() is not called.

  • The exception will be silently suppressed.

    Why it's wrong here

    Exception propagates normally unless caught.

  • The file will be automatically closed by Python's garbage collector immediately.

    Why it's wrong here

    GC may close file eventually, but not immediately and not guaranteed.

  • The file contents will be corrupted.

    Why it's wrong here

    No corruption; file remains open but not corrupted.

About these practice questions

This PCAP question is part of Courseiva's 169-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam dumps. Learn why practice questions differ from exam dumps →

How Courseiva writes practice questions · Editorial policy

Same concept, more angles

1 more way 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 Python script processes a log file line by line. If a line cannot be decoded due to an encoding error, the script should skip the line and continue. Which exception handling approach is best?

medium
  • A.Wrap the entire file reading in a try-except block without specifying exception type.
  • B.Use a try-except-else block to handle success and failure separately, exiting on failure.
  • C.Inside the loop, wrap the line decoding in a try-except UnicodeDecodeError block and continue.
  • D.Catch Exception in the outer loop and break on error.

Why C: It places the try-except block inside the loop, specifically catching `UnicodeDecodeError` for each line. This allows the script to skip only the problematic line and continue processing subsequent lines, which matches the requirement exactly.

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.