Courseiva

PCAP · topic practice

Exceptions and File I/O practice questions

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.

Courseiva uses original exam-style practice questions designed for learning and revision. The goal is to understand the concepts, recognise exam patterns, and improve through explanations — not memorise copied exam dumps.

Editorial oversight:Johnson Ajibi· MSc IT Security, IEEE Senior Member
20 questionsDomain: Exceptions and File I/O

What the exam tests

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

Practice set

Exceptions and File I/O questions

20 questions · select your answer, then reveal the explanation

Question 1mediummultiple choice
Study the full Python automation breakdown →

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?

A 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?

Which TWO of the following are valid ways to raise an exception in Python?

Question 4mediummultiple choice
Study the full Python automation breakdown →

What is the output of the code?

```python

with open('log.txt') as f:
    for line in f:
        if 'ERROR' in line:
            print('Error found:', line)

break ```

Exhibit

Refer to the exhibit.

# error.log
2025-03-15 10:23:45 ERROR: Division by zero in module calc.py line 42
2025-03-15 10:23:46 WARNING: Low disk space on /dev/sda1
2025-03-15 10:23:47 INFO: User login successful

# Python code
try:
    with open('error.log', 'r') as f:
        for line in f:
            if 'ERROR' in line:
                raise RuntimeError(line.strip())
except RuntimeError as e:
    print('Error found:', e)

You 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?

Drag and drop the steps to read a CSV file using the csv module in Python into the correct order.

Drag or tap steps into the slots.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4
5Step 5

A 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?

A 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?

Consider 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.)

Which TWO of the following file modes will create a new file if it doesn't exist? (Select exactly 2)

If the file 'log_output.txt' contains the following line: ERROR: Disk full what is the actual output?

Exhibit

Refer to the exhibit.

Exhibit:
    # log_output.txt contains:
    # INFO: Process started
    # ERROR: Disk full
    # WARN: Memory high
    # INFO: Process ended
    
    with open('log_output.txt', 'r') as f:
        for line in f:
            if 'ERROR' in line:
                print(line.strip())
    # Expected output: ERROR: Disk full

A 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?

Refer to the exhibit. The script stops with this error. Which exception type should be caught to handle this error gracefully?

Exhibit

Traceback (most recent call last):
  File "script.py", line 5, in <module>
    f = open('data.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'

Refer to the exhibit. What is the output of the code?

Exhibit

with open('file.txt', 'r') as f:
    data = f.read()
    print(f.closed)
# Output: False

Refer to the exhibit. What is the output of the code?

Exhibit

file = open('test.txt', 'w')
file.write('Hello')
file.close()
print(file.closed)

Refer to the exhibit. If 'data.txt' does not exist, what happens?

Exhibit

def read_file():
    try:
        f = open('data.txt', 'r')
        return f.read()
    finally:
        f.close()

result = read_file()

Refer to the exhibit. If 'data.txt' contains '123', what is the output?

Exhibit

try:
    f = open('data.txt', 'r')
    data = f.read()
    num = int(data)
except (ValueError, IOError) as e:
    print('Error:', e)
finally:
    f.close()

Refer to the exhibit. What is the output of this code?

Exhibit

Traceback (most recent call last):
  File "script.py", line 5, in <module>
    open('nonexistent.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'

Code:
try:
    open('nonexistent.txt', 'r')
except OSError:
    print('OS error')
except FileNotFoundError:
    print('File not found')

Refer to the exhibit. What is the output?

Exhibit

try:
    x = 1 / 0
except ZeroDivisionError:
    print('A')
except:
    print('B')
else:
    print('C')
finally:
    print('D')

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?

Free account

Track your progress over time

Create a free account to save your results and see which topics improve across sessions.

Focused Exceptions and File I/O sessions

Start a Exceptions and File I/O only practice session

Every question in these sessions is drawn from the Exceptions and File I/O domain — nothing else.

Related practice questions

Related PCAP topic practice pages

Move into related areas when this topic feels solid.

Frequently asked questions

What does the PCAP exam test 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.
How should I use these practice questions?
Select your answer before revealing the explanation. Then read why each option is right or wrong — this active recall approach builds retention far faster than re-reading notes.
Can I practise just Exceptions and File I/O questions in a focused session?
Yes — the session launcher on this page draws every question from the Exceptions and File I/O domain. Use a 10-question session first to gauge your baseline, then move to 20 or 30 once the weak spots are clear.
Where can I practise other PCAP topics?
Use the topic links above to move to related areas, or go back to the PCAP question bank to see all topics.
Are these real exam questions or dumps?
These are original practice questions written to test the same concepts the PCAP exam covers. They are not copied from any real exam or dump site.