Answer to Question #119223 in Python for Panda

Question #119223
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.
1
Expert's answer
2020-06-01T10:45:39-0400

Example 1:


a=10

b=0

try:

    #trying to divide a by b

    print(a/b)

    #his should cause an exception since the value of b is 0

except ZeroDivisionError:

    print('Cannot divide by zero')

Output:

Cannot divide by zero


#----------------------------------------------------------------------------------------------------------------------------------------------------


Example 2:


numbers=[2,3,4,None,5,6]

 #looping through numbers list

for i in range(len(numbers)):

    #starting try block

    try:

        #squaring each number

        numbers[i]=numbers[i]**2

    except TypeError:

        #some non numeric data value found in list, which caused

        #exception when trying to square

        print('Non numeric value found, ignoring')

print(numbers) # should be [4, 9, 16, None, 25, 36]

Output:

Non numeric value found, ignoring

[4, 9, 16, None, 25, 36]


#-----------------------------------------------------------------------------------------------------------------------------------------------------


Example 3:


#creating a dictionary

names_ages=dict()

# adding some key and value pairs

names_ages['alex']=25

names_ages['bayson']=24

names_ages['charles']=29

#creating a list of names

names=['alex','bobby','charles','derik']

#looping through list

for i in names:

    #starting try block

    try:

        #displaying value corresponding to the key value i

        print(i,names_ages[i])

    except KeyError:

        #i does not exist on names_ages dict

        print(i,'is an invalid key!')

Output:

alex 25

bobby is an invalid key!

charles 29

derik is an invalid key!



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