Exceptions Flashcards

Memorize exception syntax and errors (5 cards)

1
Q

What are the built-in python error types

A

SyntaxError: Invalid Python syntax
NameError: Using an undefined variable or name
ValueError: Passing an invalid value to a function
TypeError: Using an operation or function on an incompatible type
IndexError: Accessing an invalid index in a list
KeyError: Attempting to access a non-existent key in a dictionary

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the syntax for writing an exception

A

try:
number1 = int(input())
print(number1 * 3)

number2 = int(input())
print(number2 * 3) except:
print('x') print('e')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what is the syntax for exceptions with multiple exception handlers

A

user_input = input()
while user_input != ‘end’:
try:
# Possible ValueError
divisor = int(user_input)
# Possible ZeroDivisionError
print(60 // divisor) # Truncates to an integer
except ValueError:
print(‘v’)
except ZeroDivisionError:
print(‘z’)
user_input = input()
print(‘OK’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what is the syntax for raising an exception

A

try:
score = int(input(“Enter test score: “))

if score < 0:
    raise ValueError("Score cannot be negative.")

if score > 100:
    raise ValueError("Score cannot be greater than 100.")

print("Valid score entered.")

except ValueError as e:
print(e

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what is the syntax for raising an exception with a function

A

def get_age():
age = int(input(“Enter age: “))
if age < 0:
raise ValueError(“Age cannot be negative.”)
return age

try:
user_age = get_age()
print(“Your age is:”, user_age)

except ValueError as e:
print(e)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly