Exceptionexamples

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 4

Builtin exception examples

1) ZeroDivisionError (It is raised when number is divided by 0)

a=int(input())

b=int(input())

try:

c=a/b

print(c)
except ZeroDivisionError:

print("b cant be 0")

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:

print("Enter integer data only")

Example 2:

import math

try:

print(math.sqrt(-1))

except ValueError:

print("sqrt() must always accept valid type as an argument")

3) NameError (It is raised when identifier is not found in local or global namespace)

try:

print(b)

except NameError:

print("b is not defined")


4) IndexError (It is raised when the index is not found in the sequence or index is out of range)

try:

s="abcd"

print(s[4])

except IndexError:

print("index out of range")

5) KeyError (It is raised when key is not found in the dictionary)

try:

d={100:"Raju",101:"Ravi"}

print(d[102])

except KeyError:

print("Key is not present in dictionary")

6) KeyboardInterrupt (it is raised when user interrupts program execution by pressing ctrl+c)

try:

a=int(input())

print(a)

except KeyboardInterrupt:

print("program execution has been terminated by pressing ctrl-c")

7) TypeError (it is raised when invalid operation is performed among different types)

try:

s="abcd"/5

print(s)

except TypeError:

print("/ operation is not possible for strings")

8) IOError (it is raised when input or output operation fails)


try:

f=open("file.txt","r")

print(f.read())

except IOError:

print("file does not exist for reading")

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:

print("result is out of range")

10) AttributeError (it is raised when attribute reference fails)

try:

l=[1,2,3]

l.add(4)

except AttributeError as e:

print(e) #prints 'list' object has no attribute 'add'

11) ImportError (it is raised when import statement fails)


try:

import koushik

except ImportError as e:

print(e) #No module named 'koushik'

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:

print("local variable a is not defined any value but it is referenced")

f()

You might also like