PCAP · domain
Exceptions and File I/O
This domain covers Python's exception hierarchy, try/except/else/finally, raising and customizing exceptions, the with statement and context managers, and file I/O modes and methods. Questions ask you to pick correct inheritance, choose Pythonic error handling, judge with-statement claims, and select the right open() mode for a stated task.
Focused practice
Practice Exceptions and File I/O questions
Scored sessions drawing only from this domain — pick a length below.
Start 20-question practice test →What this domain covers
What to know about Exceptions and File I/O
You must define custom exceptions, write try/except/else/finally blocks, use with for safe file handling, and choose the correct open() mode. The single most important thing: know which mode truncates, appends, or reads/writes binary, and that custom exceptions should inherit from Exception.
Choosing the correct base class, such as Exception, when defining a custom exception
Using try/except/else/finally and raise to handle and propagate errors correctly
Applying the with statement and context managers for deterministic resource cleanup
Selecting open() modes like 'rb', 'wb', 'a', and 'r+' and using read, write, seek
Watch out for
Common Exceptions and File I/O exam traps
- ▸Inheriting a custom exception from BaseException instead of Exception, which bypasses normal except Exception handling
- ▸Assuming 'w' or 'wb' appends; both truncate an existing file, so 'a' or 'ab' is needed to preserve contents
- ▸Believing with replaces try/except; it manages cleanup but does not itself catch exceptions raised in the block
Question index
All Exceptions and File I/O questions (76)
Click any question to see the full explanation, or start a practice session above.
A programmer needs to write a function that reads a large binary file (over 1 GB) and returns its entire content as a bytes object. The function must handle the case where the path provided is actually a directory (IsADirectoryError) by returning an empty bytes object. Which implementation is most memory-efficient and correctly handles the directory case? Consider that reading the entire file into memory is acceptable for the business case.
Easy2Which method of a file object reads the entire content of a text file as a single string?
Easy3A 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?
Medium4A developer needs to write a function that safely divides two numbers and returns None if division by zero occurs. Which implementation is most Pythonic?
Medium5Which TWO statements about exception handling in Python are correct? (Select exactly 2.)
Medium6Match each Python data structure to its mutability.
Medium7What is the output of the following code? try: exec('1/0') except: print('error') else: print('no error') finally: print('done')
Hard8A developer opens a CSV file with open('data.csv', 'r', encoding='utf-8') and reads it with readline(). The first line contains a non-ASCII character that the file declares as UTF-8. Which exception is most likely raised if the file actually contains bytes that are not valid UTF-8?
Easy9A developer has a function that performs several operations and may raise different exceptions. The developer wants to catch a specific exception and then re-raise it after logging. Which code snippet correctly re-raises the same exception without losing its traceback?
Medium10A developer writes a helper that copies lines from one text file to another. The helper opens both files with open() inside a try block and closes them in a finally block. If an exception occurs while writing, which statement about the finally block is correct?
Hard11Which THREE of the following exception types are subclasses of OSError in Python 3?
Hard12A developer is writing a function that reads a configuration file. The function must distinguish between a missing file, a permission problem, and a malformed file, and it must not leave the file open on any path. Which TWO techniques are appropriate for this requirement? (Choose two.)
Medium13Refer to the exhibit. A developer is writing a script to read this JSON configuration file. The script should write the logging configuration to a separate file called 'logging.conf'. Which file mode should be used to create the file if it doesn't exist, and overwrite it if it does?
Medium14What will be printed?
Medium15Which of the following statements about the `finally` block is true?
Easy16A Python script that processes log files uses the following code: with open('log.txt', 'r') as f: lines = f.readlines() for line in lines: # process What is a potential inefficiency in this code?
Medium17A junior developer is writing a helper that reads a small log file and returns its contents as a single string. The file is guaranteed to exist and be readable. The helper currently uses an explicit open, a try/finally block, and manual close call. A reviewer asks for the most idiomatic Python 3 replacement that guarantees closure. Which construct should be used?
Easy18A senior developer in a team argues that using try-except blocks is slower than checking conditions with if statements. They propose replacing all try blocks that handle file I/O errors with existence checks using os.path.exists before opening files. During a code review, you recall that Python's official documentation and best practices prefer EAFP (Easier to Ask for Forgiveness than Permission) over LBYL (Look Before You Leap) in many cases, especially in concurrent environments. The team's application is a multi-threaded web server that serves static files from a shared directory. Which is the strongest counterargument against the senior developer's proposal?
Hard19Refer to the exhibit. Which of the following Python code snippets would generate this error?
Medium20Which TWO of the following are correct statements about the 'with' statement in Python file I/O?
Easy21A 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?
Easy22Match each Python module to its purpose.
Medium23Consider 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)?
Hard24Which TWO of the following are true about the 'with' statement in Python file I/O?
Medium25In Python, if you have a try block followed by an except clause that catches all exceptions, which of the following is true about the else clause?
Easy26Refer to the exhibit. If both data.txt and backup.txt do not exist, what is the output?
Hard27A developer is writing a script that processes user-uploaded CSV files. The script should attempt to read the file, and if a UnicodeDecodeError occurs, log a warning and skip the file. Which code snippet correctly achieves this without stopping the entire process?
Medium28Refer to the exhibit. What is the effect of using 'from None' in the raise statement?
Hard29A production script opens a configuration file with `open('config.ini', 'r')`. During a recent maintenance window, the file was replaced by a directory of the same name. The script now terminates with `IsADirectoryError`. The developer wants to catch this specific condition separately from a missing file and log a distinct message. Which `except` clause should be added?
Medium30Which of the following correctly raises a new exception while preserving the original traceback?
Hard31A developer is creating a custom exception hierarchy for a library. The base exception is `LibraryError`. Which definition ensures that subclasses can be caught using the parent exception, but also allows distinguishing between different error types?
Hard32Which of the following is the correct way to open a file for writing in binary mode?
Easy33A developer is building a logging system that writes logs to a file. The system should handle disk-full situations gracefully without crashing the main application. Which approach is appropriate?
Medium34Which TWO of the following are built-in exceptions in Python? (Select exactly 2.)
Easy35What is the output of the Python code after reading the config.txt file?
Hard36Consider the following code: import json try: with open('config.json') as f: data = json.load(f) except FileNotFoundError: print("Missing config file") except json.JSONDecodeError: print("Invalid JSON") except: print("Unexpected error") If the file 'config.json' exists but contains invalid JSON, what is printed?
Easy37A developer runs a script that reads records from a binary file. After a partial read, the storage device is unplugged, and the read() call raises OSError. The developer wants the script to retry the read a few times before giving up, but only for this transient I/O problem. Which exception should be caught to retry specifically on this failure?
Medium38A data-import tool must read a UTF-8 CSV file that occasionally contains bytes invalid for UTF-8. The tool should not crash, but it must record that replacement occurred so the operator can review the source. The developer opens the file with `open('data.csv', encoding='utf-8', errors='replace')` and reads it. Which outcome matches this configuration?
Hard39Which THREE of the following are true about Python's exception hierarchy?
Hard40When should you raise a specific exception class rather than a generic Exception?
Hard41Which THREE of the following are true about the `with` statement for file handling?
Hard42A file is opened with open('test.txt', 'r'). The file object's tell() method returns 0. After reading 10 characters, what does tell() return?
Medium43A backup utility writes a manifest with `with open('manifest.txt', 'w') as out:`. The developer needs to ensure that partial writes are not silently left in the file when an exception occurs mid-loop. Which two statements about using a try/except/else/finally structure around this write loop are correct? (Choose two.)
Medium44A programmer writes a context manager to manage a temporary file. The class implements __enter__ to open the file and return the handle, and __exit__ to close it. During the with body, an exception is raised. The programmer wants the exception to propagate after cleanup. What should __exit__ return in this case?
Hard45Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)
Hard46Drag and drop the steps to serialize a Python object to JSON using the json module into the correct order.
Medium47A script uses `with open('data.bin', 'rb') as f:` to read binary data. Within the block, which method should be used to read exactly 4 bytes?
Medium48What is the output of the following code? try: print(1/0) except: print('err') finally: print('fin')
Medium49A 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?
Easy50A developer wants to ensure that a file is always closed after writing, even if an exception occurs. Which approach is considered best practice in Python?
Medium51Which mode should be used when opening a file for writing such that new content is appended to the end without truncating existing content?
Easy52A 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?
Easy53Refer to the exhibit. What does the 'from None' clause do in the second raise statement?
Hard54Which of the following exception classes is NOT a direct subclass of Exception in Python?
Hard55Refer to the exhibit. If the file config.cfg exists but the user does not have read permission, what will be printed?
Easy56Which TWO of the following are appropriate techniques for logging exception details in Python? (Select exactly 2)
Medium57Refer to the exhibit. A developer ran the script and saw the above traceback. The intended behavior was to load a JSON configuration file, and if the file is missing, create a default config. What is the most likely root cause of the second exception (NameError)?
Hard58Refer to the exhibit. The above log shows an unhandled exception that caused the program to crash. The developer wants to handle this exception and log the error without crashing. Which exception type should be caught in the main code to capture this specific error?
Easy59A Python application processes user-uploaded files. The requirement is to catch any I/O-related exception while reading the file, but not to catch KeyboardInterrupt or SystemExit. Which exception type should be caught?
Hard60Refer to the exhibit. If /var/data/in.csv does not exist, what exception is raised?
Medium61Which TWO of the following are valid ways to read a file line by line without loading the entire file into memory?
Medium62Consider the following code snippet: try: x = int(input()) y = 10 / x print(y) except ZeroDivisionError: print('Division by zero') except ValueError: print('Invalid integer') If the user enters '0', what is the output?
Hard63What will be the output of the following code? try: print(1/0) except: print('error') else: print('no error') finally: print('done')
Easy64Which of the following is the correct way to open a file for writing in text mode, ensuring that if the file already exists it will be overwritten?
Easy65A developer needs to write binary data to a file. Which file mode should be used to open the file for writing in binary mode without truncating it if it already exists?
Easy66What is the output of the following code? try: raise ValueError('a') except ValueError as e: print(e.args[0]) finally: print('b')
Hard67Which TWO of the following are built-in Python exceptions?
Easy68A developer wants to ensure that a file is always closed, even if an exception occurs, without using the 'with' statement. Which approach correctly achieves this?
Medium69A developer is working on a data pipeline that processes files from untrusted sources. The pipeline should catch and log any exception, but also ensure that sensitive information from the exception (e.g., file paths) is not exposed to end users. Which approach balances security and debugging?
Hard70A programmer wants to catch both `FileNotFoundError` and `PermissionError` with a single except clause. Which tuple is correct?
Medium71A small web application allows users to download files from a server. The code uses open() without any exception handling. When a user requests a non-existent file, the server crashes with a traceback and returns a 500 Internal Server Error to the client. The team needs to modify the code to handle this situation gracefully: if the file does not exist, the application should return a 404 Not Found response (by calling a function send_404()). The application should not catch unrelated exceptions like KeyboardInterrupt. Which modification is the most appropriate?
Easy72A pipeline processes many small binary records. The developer writes a custom exception `class RecordError(Exception)` with an `__init__` that stores a record identifier and calls `super().__init__(message)`. A validation function raises `RecordError` for a corrupt record, and a worker catches it to log the identifier. The worker also wants the raw message to be available via `str(e)`. Which statement about this design is correct?
Hard73A developer is implementing a custom exception for invalid data. Which class should the custom exception inherit from?
Medium74A 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?
Easy75Which TWO of the following are correct ways to raise a custom exception in Python? (Assume CustomError and CustomException are user-defined.)
Easy76A 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'.)
MediumOther domains
All PCAP exam domains
Frequently asked questions
- What does the Exceptions and File I/O domain cover on the PCAP exam?
- You must define custom exceptions, write try/except/else/finally blocks, use with for safe file handling, and choose the correct open() mode. The single most important thing: know which mode truncates, appends, or reads/writes binary, and that custom exceptions should inherit from Exception.
- How many questions are in this domain?
- This page lists all 76 Exceptions and File I/O questions in the PCAP question bank. The actual exam draws from this domain proportionally to its weighting in the official exam blueprint.
- What is the best way to practise this domain?
- Start with a short focused session (10 questions) to identify gaps, then work through explanations. Repeat with a longer session once the weak areas feel solid.
- Can I practise only Exceptions and File I/O questions?
- Yes — the session launcher on this page filters questions to this domain only. Choose any session length for inline explanations and scoring.