116k views
3 votes
Code Example 8-1

import csv
import sys
FILENAME = "names.csv"
def main():
try:
names = []
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
for row in reader:
names.append(row)
except FileNotFoundError as e:
print("Could not find " + FILENAME + " file.")
sys.exit()
except Exception as e:
print(type(e), e)
sys.exit()
print(names)
if __name__ == "__main__":
main()
Refer to Code Example 8-1. If the names.csv file is not in the same directory as the file that contains the Python code, what type of exception will be thrown and caught?
A. FileNotFoundError
B. OSError
C. Exception
D. All of the above

User Euvs
by
6.0k points

1 Answer

4 votes

Answer:

Option A: FileNotFoundError

Step-by-step explanation:

FileNotFoundError is an exception which is thrown when a program fail to open a specified file. The root causes of this type of error can be:

  1. The directory path to locate a target file is wrongly defined in our code due to a typo on the file name or misuse of relative directory path, such as ../ and ./ which denote two different paths.
  2. For some reasons, a target file is misplaced in a wrong directory.

Any one of the above reasons can lead to the exception to be thrown when the file doesn't exist.

User Tom Maxwell
by
6.2k points