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.
Start practicing
Exceptions and File I/O — choose a session length
Free · No account required
Domain overview
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.
Exam objectives
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
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
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?
2Which 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?
3A 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?
4Consider 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?
5Which of the following statements about the `finally` block is true?
6A programmer wants to catch both `FileNotFoundError` and `PermissionError` with a single except clause. Which tuple is correct?
7Which THREE of the following are true about the `with` statement for file handling?
8Which TWO of the following are built-in Python exceptions?
9What is the output of the Python code after reading the config.txt file?
10Drag and drop the steps to serialize a Python object to JSON using the json module into the correct order.
11Match each Python data structure to its mutability.
12Match each Python module to its purpose.
13A 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?
14A 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?
15A 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?
16A 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?
17A 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?
18A 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?
19A 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?
20Which TWO statements about exception handling in Python are correct? (Select exactly 2.)
21Which TWO of the following are built-in exceptions in Python? (Select exactly 2.)
22Refer 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)?
23Refer 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?
24Refer 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?
25A 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?
26Which of the following is the correct way to open a file for writing in binary mode?
27Which method of a file object reads the entire content of a text file as a single string?
28What is the output of the following code? try: print(1/0) except: print('err') finally: print('fin')
29A 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?
30A file is opened with open('test.txt', 'r'). The file object's tell() method returns 0. After reading 10 characters, what does tell() return?
31What is the output of the following code? try: raise ValueError('a') except ValueError as e: print(e.args[0]) finally: print('b')
32Which of the following correctly raises a new exception while preserving the original traceback?
33What is the output of the following code? try: exec('1/0') except: print('error') else: print('no error') finally: print('done')
34Which TWO of the following are appropriate techniques for logging exception details in Python? (Select exactly 2)
35Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)
36Refer to the exhibit. If the file config.cfg exists but the user does not have read permission, what will be printed?
37Refer to the exhibit. Which of the following Python code snippets would generate this error?
38Refer to the exhibit. If both data.txt and backup.txt do not exist, what is the output?
39In 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?
40A developer needs to write a function that safely divides two numbers and returns None if division by zero occurs. Which implementation is most Pythonic?
41Consider 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)?
42Which mode should be used when opening a file for writing such that new content is appended to the end without truncating existing content?
43A 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?
44Which of the following exception classes is NOT a direct subclass of Exception in Python?
45What will be the output of the following code? try: print(1/0) except: print('error') else: print('no error') finally: print('done')
46A 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?
47When should you raise a specific exception class rather than a generic Exception?
48Which TWO of the following are valid ways to read a file line by line without loading the entire file into memory?
49Which THREE of the following are true about Python's exception hierarchy?
50Which TWO of the following are correct statements about the 'with' statement in Python file I/O?
51What will be printed?
52Consider 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?
53A 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?
54A 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?
55A developer is implementing a custom exception for invalid data. Which class should the custom exception inherit from?
56Which TWO of the following are true about the 'with' statement in Python file I/O?
57Which THREE of the following exception types are subclasses of OSError in Python 3?
58Which TWO of the following are correct ways to raise a custom exception in Python? (Assume CustomError and CustomException are user-defined.)
59A 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?
60A 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?
61A 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?
62A 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'.)
63A 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.
64Refer to the exhibit. What does the 'from None' clause do in the second raise statement?
65Refer to the exhibit. What is the effect of using 'from None' in the raise statement?
66Refer to the exhibit. If /var/data/in.csv does not exist, what exception is raised?
67A 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?
68A 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?
69A 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?
70A 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?
71A 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?
72A 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.)
73A 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?
74A 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?
75A 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.)
76A 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?
Deep-dive questions
The most-searched questions in this domain — detailed explanations, worked examples, full answer breakdowns.
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.
The Courseiva PCAP question bank contains 76 questions in the Exceptions and File I/O domain, covering the 36% of the exam attributed to this domain in the official Python Institute blueprint. 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