Describe how catching exception can help with file errors. Write three python examples that actually generate file errors in your computer and catch the errors with try: except: blocks. Include the code and output for each example in your post.
Python, exceptions are handled using a try statement. Any operation that raise an exception is put inside the try clause. except clause is used to handle the exceptions. Below is the code example:
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))
Comments
Leave a comment