nerdexam
Cisco

350-901 · Question #13

open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file)

The correct answer is A. try: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file) except: print("file not there"). Proper Python exception handling wraps all file operations in the try block so that any failure - including file not found - is caught by the except block.

Software Development and Design

Question

open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file)

Options

  • Atry: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file) except: print("file not there")
  • Btry: print("file not there") except: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file)
  • Ctry: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file) except: print("file not there") catch: error(read_file)
  • Dopen_file = open("text_file.txt", "r") read_file = open_file.read() try: print(read_file) except: print("file not there")

How the community answered

(19 responses)
  • A
    79% (15)
  • B
    5% (1)
  • C
    5% (1)
  • D
    11% (2)

Why each option

Proper Python exception handling wraps all file operations in the try block so that any failure - including file not found - is caught by the except block.

Atry: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file) except: print("file not there")Correct

Placing all three file operations (open, read, print) inside the try block ensures that any exception raised at any step - such as FileNotFoundError if the file does not exist - is caught by the except clause, which then prints a user-friendly error message. This is the correct pattern for handling file I/O errors in Python.

Btry: print("file not there") except: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file)

The try block only contains the print statement, so the open and read calls outside it would raise an unhandled exception before execution ever reaches the try.

Ctry: open_file = open("text_file.txt", "r") read_file = open_file.read() print(read_file) except: print("file not there") catch: error(read_file)

Python does not have a catch keyword; the language uses except for exception handling, making this code a syntax error.

Dopen_file = open("text_file.txt", "r") read_file = open_file.read() try: print(read_file) except: print("file not there")

The open call is outside the try block, so a FileNotFoundError during open would be unhandled even though print is wrapped.

Concept tested: Python try/except error handling for file I/O

Source: https://docs.python.org/3/tutorial/errors.html

Topics

#Python#Error Handling#File I/O#Exception Handling

Community Discussion

No community discussion yet for this question.

Full 350-901 Practice