Practice PCAP Exceptions and File I/O questions with full explanations on every answer.
Start practicing
Exceptions and File I/O — choose a session length
Free · No account required
Click any question to see the full explanation and answer options, or start a focused practice session above.
A 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?
2A 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?
3A developer implements a custom exception class `DataError` that inherits from `Exception`. Which method override is essential to ensure the exception message is properly displayed when caught?
4Which 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?
5A 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?
6Consider 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?
7Which of the following statements about the `finally` block is true?
8A programmer wants to catch both `FileNotFoundError` and `PermissionError` with a single except clause. Which tuple is correct?
9Which TWO of the following are valid ways to raise an exception in Python?
10Which THREE of the following are true about the `with` statement for file handling?
11Which TWO of the following are built-in Python exceptions?
12What is the output of the Python code after reading the config.txt file?
13What is the output of the code?
14You are a Python developer at a financial firm. Your team maintains a high-frequency trading system that reads real-time market data from a binary file 'market_feed.bin'. The file is updated every millisecond by an external process. Your script uses a `with` statement to open the file in binary read mode and reads exactly 1024 bytes each iteration in an infinite loop. Recently, the script has been crashing intermittently with an `OSError` with message '[Errno 9] Bad file descriptor'. The error occurs at random times, sometimes after minutes, sometimes after hours. The system runs on Linux. The script runs as a daemon. You suspect the issue is related to file descriptor exhaustion or the external process manipulating the file. What is the most likely cause and the best course of action?
15Drag and drop the steps to read a CSV file using the csv module in Python into the correct order.
16Drag and drop the steps to serialize a Python object to JSON using the json module into the correct order.
17Match each Python data structure to its mutability.
18Match each Python module to its purpose.
19A 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?
20A 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?
21A developer is implementing a custom context manager to manage database connections. The context manager should automatically roll back the transaction if an exception occurs, but commit if no exception occurs. Which pattern ensures this behavior correctly?
22A 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?
23A 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?
24A 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?
25A developer writes a script that opens a file for reading. The script must ensure that the file is closed even if an exception occurs during reading. Which pattern guarantees proper resource cleanup?
26A 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?
27A 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?
28Which TWO statements about exception handling in Python are correct? (Select exactly 2.)
29Consider the following code snippet: x = [1, 2, 3] try: print(x[5]) except IndexError: print('Index') except LookupError: print('Lookup') Which THREE statements about this code are correct? (Select exactly 3.)
30Which TWO of the following are built-in exceptions in Python? (Select exactly 2.)
31Refer 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)?
32Refer 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?
33Refer 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?
34A 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?
35Which of the following is the correct way to open a file for writing in binary mode?
36Which method of a file object reads the entire content of a text file as a single string?
37What is the output of the following code? try: print(1/0) except: print('err') finally: print('fin')
38A 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?
39A file is opened with open('test.txt', 'r'). The file object's tell() method returns 0. After reading 10 characters, what does tell() return?
40What is the output of the following code? try: raise ValueError('a') except ValueError as e: print(e.args[0]) finally: print('b')
41Which of the following correctly raises a new exception while preserving the original traceback?
42What is the output of the following code? try: exec('1/0') except: print('error') else: print('no error') finally: print('done')
43Which TWO of the following file modes will create a new file if it doesn't exist? (Select exactly 2)
44Which TWO of the following are appropriate techniques for logging exception details in Python? (Select exactly 2)
45Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)
46Refer to the exhibit. If the file config.cfg exists but the user does not have read permission, what will be printed?
47Refer to the exhibit. Which of the following Python code snippets would generate this error?
48Refer to the exhibit. If both data.txt and backup.txt do not exist, what is the output?
49In 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?
50A developer needs to write a function that safely divides two numbers and returns None if division by zero occurs. Which implementation is most Pythonic?
51Consider 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)?
52Which mode should be used when opening a file for writing such that new content is appended to the end without truncating existing content?
53A 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?
54Which of the following exception classes is NOT a direct subclass of Exception in Python?
55What will be the output of the following code? try: print(1/0) except: print('error') else: print('no error') finally: print('done')
56A 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?
57When should you raise a specific exception class rather than a generic Exception?
58Which TWO of the following are valid ways to read a file line by line without loading the entire file into memory?
59Which THREE of the following are true about Python's exception hierarchy?
60Which TWO of the following are correct statements about the 'with' statement in Python file I/O?
61What will be printed?
62If the file 'log_output.txt' contains the lines shown, what is the actual output?
63If the file 'config.json' exists but contains invalid JSON, what is printed?
64A 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?
65A function attempts to write to a file and needs to ensure the file is closed even if an exception occurs. Which code snippet guarantees closure?
66A 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?
67A developer is implementing a custom exception for invalid data. Which class should the custom exception inherit from?
68Which TWO of the following are true about the 'with' statement in Python file I/O?
69Which THREE of the following exception types are subclasses of OSError in Python 3?
70Which TWO of the following are correct ways to raise a custom exception in Python? (Assume CustomError and CustomException are user-defined.)
71A 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?
72A 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?
73A 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?
74A 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'.)
75A 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.
76Refer to the exhibit. The script stops with this error. Which exception type should be caught to handle this error gracefully?
77Refer to the exhibit. What is the output of the code?
78Refer to the exhibit. What does the 'from None' clause do in the second raise statement?
79Refer to the exhibit. What is the output of the code?
80Refer to the exhibit. If 'data.txt' does not exist, what happens?
The Exceptions and File I/O domain covers the key concepts tested in this area of the PCAP exam blueprint published by Python Institute. Courseiva provides free domain-focused practice, mock exams, missed-question review, and readiness tracking across all PCAP domains — no account required.
The Courseiva PCAP question bank contains 80 questions in the Exceptions and File I/O domain. Click any question to see the full explanation and answer breakdown.
Start with a 10-question focused session to identify your baseline accuracy in this domain. Read every explanation — even for questions you answer correctly — to understand the reasoning. Once you score consistently above 80%, move to a 20–30 question session to confirm depth before moving to the next domain.
Yes — the session launcher on this page draws questions exclusively from the Exceptions and File I/O domain. Choose 10, 20, 30, or 50 questions for a focused session, or click individual questions to review them one by one.
Save your results, see per-domain analytics, and get readiness scores — free, for every certification.
Sign Up FreeFree forever · Every certification included