nerdexam
CiscoCisco

350-901 · Question #13

350-901 Question #13: Real Exam Question with Answer & Explanation

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

Explanation

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.

Common mistakes.

  • B. 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.
  • C. Python does not have a catch keyword; the language uses except for exception handling, making this code a syntax error.
  • D. 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

Reference. 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 PracticeBrowse All 350-901 Questions