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!
Comments
Leave a comment