Professional Documents
Culture Documents
Exceptionexamples
Exceptionexamples
Exceptionexamples
a=int(input())
b=int(input())
try:
c=a/b
print(c)
except ZeroDivisionError:
2) ValueError (It is raised when the arguments passed to the function are of invalid data type)
Example 1:
try:
a=int(input())
print(a)
except ValueError:
Example 2:
import math
try:
print(math.sqrt(-1))
except ValueError:
3) NameError (It is raised when identifier is not found in local or global namespace)
try:
print(b)
except NameError:
try:
s="abcd"
print(s[4])
except IndexError:
try:
d={100:"Raju",101:"Ravi"}
print(d[102])
except KeyError:
6) KeyboardInterrupt (it is raised when user interrupts program execution by pressing ctrl+c)
try:
a=int(input())
print(a)
except KeyboardInterrupt:
7) TypeError (it is raised when invalid operation is performed among different types)
try:
s="abcd"/5
print(s)
except TypeError:
f=open("file.txt","r")
print(f.read())
except IOError:
9) OverflowError (it is raised when maximum limit of numeric type is exceeded during calculation)
try:
import math
print(math.pow(2000,1456))
except OverflowError:
try:
l=[1,2,3]
l.add(4)
except AttributeError as e:
import koushik
except ImportError as e:
12) UnboundLocalError (it is raised when attempt is made to access local variable in function when no value has
been assigned to it)
a=20
def f():
try:
a=a+1
print(a)
except UnboundLocalError:
f()