Answer to Question #284986 in Python for ugjkyg

Question #284986

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.


1
Expert's answer
2022-01-05T16:25:10-0500

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





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS