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.

HomeCertificationsPCAPDomainsExceptions and File I/O
PCAPFree — No Signup

Exceptions and File I/O

Practice PCAP Exceptions and File I/O questions with full explanations on every answer.

80questions

Start practicing

Exceptions and File I/O — choose a session length

10 questions~10 min20 questions~20 min30 questions~30 min50 questions~50 min

Free · No account required

PCAP Domains

Modules and PackagesStringsObject-Oriented ProgrammingExceptions and File I/O

Practice Exceptions and File I/O questions

10Q20Q30Q50Q

All PCAP Exceptions and File I/O questions (80)

Start session

Click any question to see the full explanation and answer options, or start a focused practice session above.

1

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?

2

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?

3

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?

4

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?

5

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?

6

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?

7

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

8

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

9

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

10

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

11

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

12

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

13

What is the output of the code?

14

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?

15

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

16

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

17

Match each Python data structure to its mutability.

18

Match each Python module to its purpose.

19

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?

20

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?

21

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?

22

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?

23

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?

24

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?

25

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?

26

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?

27

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?

28

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

29

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

30

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

31

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

32

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?

33

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?

34

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?

35

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

36

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

37

What is the output of the following code? try: print(1/0) except: print('err') finally: print('fin')

38

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?

39

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?

40

What is the output of the following code? try: raise ValueError('a') except ValueError as e: print(e.args[0]) finally: print('b')

41

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

42

What is the output of the following code? try: exec('1/0') except: print('error') else: print('no error') finally: print('done')

43

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

44

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

45

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

46

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

47

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

48

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

49

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?

50

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?

51

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

52

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

53

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?

54

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

55

What will be the output of the following code? try: print(1/0) except: print('error') else: print('no error') finally: print('done')

56

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?

57

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

58

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

59

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

60

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

61

What will be printed?

62

If the file 'log_output.txt' contains the lines shown, what is the actual output?

63

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

64

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?

65

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?

66

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?

67

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

68

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

69

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

70

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

71

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?

72

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?

73

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?

74

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

75

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.

76

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

77

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

78

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

79

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

80

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

Practice all 80 Exceptions and File I/O questions

Other PCAP exam domains

Modules and PackagesStringsObject-Oriented Programming

Frequently asked questions

What does the Exceptions and File I/O domain cover on the PCAP exam?

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.

How many Exceptions and File I/O questions are in the PCAP question bank?

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.

What is the best way to practice Exceptions and File I/O for PCAP?

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.

Can I practice only Exceptions and File I/O questions for PCAP?

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.

Free forever · No credit card required

Track your PCAP domain progress

Save your results, see per-domain analytics, and get readiness scores — free, for every certification.

Sign Up Free

Free forever · Every certification included

Practice Session

10 questions20 questions30 questions50 questions

Study Resources

All DomainsPractice TestMock ExamFlashcardsStudy Guide