Describe how catching exceptions can help with file errors. Write three Python examples that actually generate file errors on your computer and catch the errors with try: except: blocks. Include the code and output for each example in your post.
Describe how you might deal with each error if you were writing a large production program. These descriptions should be general ideas in English, not actual Python code.
Example-1
def get_sum_even(lst):
Sum=0;
for c in range(0,len(lst)):
is_int = True
try:
# convert to integer
int(str(lst[c]))
except ValueError:
is_int = False
if(is_int):
if( lst[c]%2==0):
Sum = Sum + lst[c]
return(Sum)
s = [2, 3, 5, 4, -1, 2]
print(s)
print("Sum = %d"%get_sum_even(s))
s = [1, 2, 3, 4, 'two',2]
print("\n",s)
print("Sum = %d"%get_sum_even(s))
s = []
print("\n",s)
print("Sum = %d"%get_sum_even(s))
s = ['NA']
print("\n",s)
print("Sum = %d"%get_sum_even(s))
Example-2
def divide(f1, f2):
try:
answer = f1/f2
return answer
except ZeroDivisionError:
return 'Divide by zero is not allowed'
print(divide(10,5))
print(divide(10,0))
Example-3
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
Comments
Leave a comment