Examples of Exception
1. Index error
2. Key error
3. Value error and type error
4. Zero division error
When these errors occur
L=[10, 20, 30, 40, 50]
index=int(input(‘enter a index’) # user has to enter value here
print(L[index])
Program:
L=[10, 20, 30, 40, 50] # LIST OF ELEMENT
index= int(input(‘Enter index’)) # ASKING USER TO ENTER INDEX
print(L[index])
• If we print valid index it will print else
• If not valid index it will print error
• So ,user itself is responsible for giving wrong index
What our program can do ?
• It can give a message”please enter a index which is from 0 to 4 only”
• Now there in output the error will be given as traceback, means it is showing in which line the
error is appearing.
Index error: List index out of range
Name of the error. This is the description of the error
Value Error and Type error:
val= int(‘abc’) # here we are doing type conversion
res=‘2’+3 # this type is called as value error
We are saying here ‘2’+3
2 to be concatenate with 3
But it is a string how can a type int be concatenated with string
a=10
s=‘number’ THIS IS TYPE ERROR
print(s+a)
Key error:
D=[1:’a’, 2:’b’, 3:’c’]# dictionary list
key=int(input(‘Enter a key’))
print(L[key])
D={1:’a’, 2:’b’, 3:’c’}
key= int(input(‘Enter a key’))
print(D[key]) # it will show key error
Two possibilities of getting an error
1. Not entering a proper key and
2. entering string instead of integers
Zero Division Error:
a= int(input(‘Enter rst number’)
b=int(input(‘Enter second number’)
res=a//b
print(res)# it will show zero division error
fi