CPT168 Unit 8 quiz

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

The finally clause of a try statement

is executed whether or not an exception has been thrown

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?

FileNotFoundError

If a program attempts to read from a file that does not exist, which of the following will catch that error?

FileNotFoundError and OSError

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 for statement in the try clause refers to readers instead of reader, what type exception will be thrown and caught?

NameError

Within the try clause of a try statement, you code

a block of statements that might cause an exception

A Python program should use try statements to handle

all exceptions that can't be prevented by normal coding techniques

It's a common practice to throw your own exceptions to test error handling routines that

catch exceptions that are hard to produce otherwise

To cancel the execution of a program in the catch clause of a try statement, you can use the

exit() function of the sys module

To throw an exception with Python code, you use the

raise statement

When an exception is thrown, Python creates an exception object that contains all but one of the following items of information. Which one is it?

the severity of the exception

Which of the following is the correct way to code a try statement that catches any type of exception that can occur in the try clause?

try: number = float(input("Enter a number: ")) print("Your number is: ", number) except: print("Invalid number.")

Which of the following is the correct way to code a try statement that displays the type and message of the exception that's caught?

try: number = int(input("Enter a number: ")) print("Your number is: ", number) except Exception as e: print(type(e), e)


Set pelajaran terkait

Chapter 4: Life Insurance Policy Provisions, Options, and Riders

View Set

Employment Law: Chapter 3: Title VII of the Civil Rights Act of 1964

View Set

Spanish Vocab by VE con el Expansión de Vocabulario

View Set