Courseiva
Knowledge + Practice
CertificationsVendorsCareer RoadmapsLabs & ToolsStudy GuidesGlossaryPractice Questions
C
Courseiva

Free IT certification practice questions with explained answers for CCNA, CompTIA, AWS, Azure, Google Cloud, and more.

Certification Practice Questions

CCNA practice questionsSecurity+ SY0-701 practice questionsAWS SAA-C03 practice questionsAZ-104 practice questionsAZ-900 practice questionsCLF-C02 practice questionsA+ Core 1 practice questionsGoogle Cloud ACE practice questionsCySA+ CS0-003 practice questionsNetwork+ N10-009 practice questions
View all certifications →

Product

CertificationsCertification PathsExam TopicsPractice TestsExam Dumps vs Practice TestsStudy HubComparisons

Company

AboutContactEditorial PolicyQuestion Writing PolicyTrust Center

Legal

Privacy PolicyTerms of Service

Courseiva is a free IT certification practice platform offering original exam-style practice questions, detailed explanations, topic-based practice, mock exams, readiness tracking, and study analytics for Cisco, CompTIA, Microsoft, AWS, and other technology certifications.

© 2026 Courseiva. Courseiva is operated by JTNetSolutions Ltd. All rights reserved.

Courseiva is an independent certification practice platform and is not affiliated with, endorsed by, or sponsored by Cisco, Microsoft, AWS, CompTIA, Google, ISC2, ISACA, or any other certification vendor. Vendor names and certification marks are used only to identify the exams learners are preparing for.

← Exceptions and File I/O practice sets

PCAP Exceptions and File I/O • Complete Question Bank

PCAP Exceptions and File I/O — All Questions With Answers

Complete PCAP Exceptions and File I/O question bank — all 0 questions with answers and detailed explanations.

80
Questions
Free
No signup
Certifications/PCAP/Practice Test/Exceptions and File I/O/All Questions
Question 1easymultiple choice
Read the full Exceptions and File I/O explanation →

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?

Question 2mediummultiple 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?

Question 3hardmultiple choice
Read the full Exceptions and File I/O explanation →

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?

Question 4easymultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 5mediummultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 6hardmultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 7easymultiple choice
Read the full Exceptions and File I/O explanation →

Which of the following statements about the `finally` block is true?

Question 8mediummultiple choice
Read the full Exceptions and File I/O explanation →

A programmer wants to catch both `FileNotFoundError` and `PermissionError` with a single except clause. Which tuple is correct?

Question 9mediummulti select
Study the full Python automation breakdown →

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

Question 10hardmulti select
Read the full Exceptions and File I/O explanation →

Which THREE of the following are true about the `with` statement for file handling?

Question 11easymulti select
Study the full Python automation breakdown →

Which TWO of the following are built-in Python exceptions?

Question 12hardmultiple choice
Study the full Python automation breakdown →

What is the output of the Python code after reading the config.txt file?

Exhibit

Refer to the exhibit.

# config.txt
[Settings]
host = localhost
port = 8080
debug = True

# Python code
import configparser

config = configparser.ConfigParser()
config.read('config.txt')
port = config.getint('Settings', 'port')
print(port)
Question 13mediummultiple choice
Read the full Exceptions and File I/O explanation →

What is the output of the code?

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)
Question 14hardmultiple choice
Study the full Python automation breakdown →

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?

Question 15mediumdrag order
Study the full Python automation breakdown →

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

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4
5Step 5
Question 16mediumdrag order
Study the full Python automation breakdown →

Drag and drop the steps to serialize a Python object to JSON using the json module into the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4
5Step 5
Question 17mediummatching
Study the full Python automation breakdown →

Match each Python data structure to its mutability.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Mutable

Immutable

Mutable

Immutable

Mutable

Question 18mediummatching
Study the full Python automation breakdown →

Match each Python module to its purpose.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Mathematical functions

Generate pseudo-random numbers

Manipulate dates and times

Work with JSON data

Interact with operating system

Question 19easymultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 20mediummultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 21hardmultiple choice
Read the full NAT/PAT explanation →

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?

Question 22easymultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 23mediummultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 24hardmultiple choice
Read the full NAT/PAT explanation →

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

Question 25easymultiple choice
Read the full NAT/PAT explanation →

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?

Question 26mediummultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 27hardmultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 28mediummulti select
Study the full Python automation breakdown →

Which TWO statements about exception handling in Python are correct? (Select exactly 2.)

Question 29hardmulti select
Read the full Exceptions and File I/O explanation →

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

Question 30easymulti select
Study the full Python automation breakdown →

Which TWO of the following are built-in exceptions in Python? (Select exactly 2.)

Question 31hardmultiple choice
Read the full Exceptions and File I/O explanation →

Refer 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)?

Exhibit

Traceback (most recent call last):
  File "app.py", line 9, in <module>
    with open("config.json", "r") as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'config.json'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 11, in <module>
    config = json.load(f)
             ^^^^^^^^^^^
NameError: name 'json' is not defined
Question 32mediummultiple choice
Read the full Exceptions and File I/O explanation →

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

Exhibit

{
  "logging": {
    "level": "DEBUG",
    "file": "/var/log/app.log"
  },
  "database": {
    "host": "localhost",
    "port": 5432
  }
}
Question 33easymultiple choice
Read the full Exceptions and File I/O explanation →

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

Exhibit

2025-04-01 10:23:45 ERROR root: Unhandled exception
Traceback (most recent call last):
  File "process.py", line 15, in <module>
    process_data()
  File "process.py", line 7, in process_data
    raise ValueError('Invalid value')
ValueError: Invalid value
Question 34easymultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 35easymultiple choice
Read the full Exceptions and File I/O explanation →

Which of the following is the correct way to open a file for writing in binary mode?

Question 36easymultiple choice
Read the full Exceptions and File I/O explanation →

Which method of a file object reads the entire content of a text file as a single string?

Question 37mediummultiple choice
Read the full Exceptions and File I/O explanation →

What is the output of the following code?

try:
    print(1/0)
except:
    print('err')

finally:

print('fin')
Question 38mediummultiple choice
Study the full Python automation breakdown →

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

Question 39mediummultiple choice
Read the full Exceptions and File I/O explanation →

A file is opened with open('test.txt', 'r'). The file object's tell() method returns 0. After reading 10 characters, what does tell() return?

Question 40hardmultiple choice
Read the full Exceptions and File I/O explanation →

What is the output of the following code?

try:

raise ValueError('a') except ValueError as e:

print(e.args[0])

finally:

print('b')
Question 41hardmultiple choice
Read the full Exceptions and File I/O explanation →

Which of the following correctly raises a new exception while preserving the original traceback?

Question 42hardmultiple choice
Read the full Exceptions and File I/O explanation →

What is the output of the following code?

try:

exec('1/0')

except:
    print('error')

else:

print('no error')

finally:

print('done')
Question 43easymulti select
Read the full Exceptions and File I/O explanation →

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

Question 44mediummulti select
Study the full Python automation breakdown →

Which TWO of the following are appropriate techniques for logging exception details in Python? (Select exactly 2)

Question 45hardmulti select
Study the full Python automation breakdown →

Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)

Question 46easymultiple choice
Read the full Exceptions and File I/O explanation →

Refer to the exhibit. If the file config.cfg exists but the user does not have read permission, what will be printed?

Exhibit

try:
    with open('config.cfg', 'r') as f:
        data = f.read()
except FileNotFoundError:
    print('File not found')
except PermissionError:
    print('Permission denied')
Question 47mediummultiple choice
Study the full Python automation breakdown →

Refer to the exhibit. Which of the following Python code snippets would generate this error?

Exhibit

[ERROR] 2025-01-01 12:00:00: Unhandled exception: ValueError: invalid literal for int() with base 10: 'abc'
Question 48hardmultiple choice
Read the full Exceptions and File I/O explanation →

Refer to the exhibit. If both data.txt and backup.txt do not exist, what is the output?

Exhibit

try:
    with open('data.txt') as f:
        print(f.read())
except FileNotFoundError:
    try:
        with open('backup.txt') as f:
            print(f.read())
    except FileNotFoundError:
        print('No file found')
Question 49easymultiple choice
Study the full Python automation breakdown →

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

Question 50mediummultiple choice
Study the full Python automation breakdown →

A developer needs to write a function that safely divides two numbers and returns None if division by zero occurs. Which implementation is most Pythonic?

Question 51hardmultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 52easymultiple choice
Read the full Exceptions and File I/O explanation →

Which mode should be used when opening a file for writing such that new content is appended to the end without truncating existing content?

Question 53mediummultiple choice
Study the full Python automation breakdown →

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

Question 54hardmultiple choice
Study the full Python automation breakdown →

Which of the following exception classes is NOT a direct subclass of Exception in Python?

Question 55easymultiple choice
Read the full Exceptions and File I/O explanation →

What will be the output of the following code?

try:
        print(1/0)
    except:
        print('error')

else:

print('no error')

finally:

print('done')
Question 56mediummultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 57hardmultiple choice
Read the full Exceptions and File I/O explanation →

When should you raise a specific exception class rather than a generic Exception?

Question 58mediummulti select
Read the full Exceptions and File I/O explanation →

Which TWO of the following are valid ways to read a file line by line without loading the entire file into memory?

Question 59hardmulti select
Study the full Python automation breakdown →

Which THREE of the following are true about Python's exception hierarchy?

Question 60easymulti select
Study the full Python automation breakdown →

Which TWO of the following are correct statements about the 'with' statement in Python file I/O?

Question 61mediummultiple choice
Read the full Exceptions and File I/O explanation →

What will be printed?

Exhibit

Refer to the exhibit.

Exhibit:
    def parse_value(data):
        try:
            value = int(data)
            return value
        except ValueError:
            return None
        except TypeError:
            return None
        except:
            return -1
    
    result = parse_value('abc')
    print(result)
Question 62hardmultiple choice
Read the full Exceptions and File I/O explanation →

If the file 'log_output.txt' contains the lines shown, 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
Question 63easymultiple choice
Read the full Exceptions and File I/O explanation →

If the file 'config.json' exists but contains invalid JSON, what is printed?

Exhibit

Refer to the exhibit.

Exhibit:
    try:
        with open('config.json', 'r') as f:
            data = json.load(f)
    except FileNotFoundError:
        print('Missing config file')
    except json.JSONDecodeError:
        print('Invalid JSON')
    except Exception:
        print('Unexpected error')
Question 64easymultiple choice
Study the full Python automation breakdown →

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

Question 65mediummultiple choice
Read the full Exceptions and File I/O explanation →

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?

Question 66hardmultiple choice
Study the full Python automation breakdown →

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

Question 67mediummultiple choice
Read the full Exceptions and File I/O explanation →

A developer is implementing a custom exception for invalid data. Which class should the custom exception inherit from?

Question 68mediummulti select
Study the full Python automation breakdown →

Which TWO of the following are true about the 'with' statement in Python file I/O?

Question 69hardmulti select
Study the full Python automation breakdown →

Which THREE of the following exception types are subclasses of OSError in Python 3?

Question 70easymulti select
Study the full Python automation breakdown →

Which TWO of the following are correct ways to raise a custom exception in Python? (Assume CustomError and CustomException are user-defined.)

Question 71mediummultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 72easymultiple choice
Read the full Exceptions and File I/O explanation →

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

Question 73hardmultiple choice
Study the full Python automation breakdown →

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

Question 74mediummultiple choice
Read the full Exceptions and File I/O explanation →

A 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'.)

Question 75easymultiple choice
Read the full NAT/PAT explanation →

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.

Question 76hardmultiple choice
Read the full Exceptions and File I/O explanation →

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'
Question 77mediummultiple choice
Read the full Exceptions and File I/O explanation →

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
Question 78hardmultiple choice
Read the full Exceptions and File I/O explanation →

Refer to the exhibit. What does the 'from None' clause do in the second raise statement?

Exhibit

Traceback (most recent call last):
  File "app.py", line 10, in <module>
    raise ValueError('Invalid value')
ValueError: Invalid value

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 12, in <module>
    raise TypeError('Type mismatch') from None
TypeError: Type mismatch
Question 79mediummultiple choice
Read the full Exceptions and File I/O explanation →

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)
Question 80hardmultiple choice
Read the full Exceptions and File I/O explanation →

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()

Practice tests

Scored 10-question sessions with instant feedback and explanations.

PCAP Practice Test 1 — 10 Questions→PCAP Practice Test 2 — 10 Questions→PCAP Practice Test 3 — 10 Questions→PCAP Practice Test 4 — 10 Questions→PCAP Practice Test 5 — 10 Questions→PCAP Practice Exam 1 — 20 Questions→PCAP Practice Exam 2 — 20 Questions→PCAP Practice Exam 3 — 20 Questions→PCAP Practice Exam 4 — 20 Questions→Free PCAP Practice Test 1 — 30 Questions→Free PCAP Practice Test 2 — 30 Questions→Free PCAP Practice Test 3 — 30 Questions→PCAP Practice Questions 1 — 50 Questions→PCAP Practice Questions 2 — 50 Questions→PCAP Exam Simulation 1 — 100 Questions→

Practice by domain

Each domain maps to a weighted exam section. Focus on the domain where you are weakest.

Modules and PackagesStringsObject-Oriented ProgrammingExceptions and File I/O

Practice by scenario

Filter questions by type — troubleshooting, exhibit, drag-and-drop, PBQ, ACLs, OSPF, and more.

Browse scenarios→

Continue studying

All Exceptions and File I/O setsAll Exceptions and File I/O questionsPCAP Practice Hub