Adobe Scan 10 Sep 2024
Adobe Scan 10 Sep 2024
Exception Handlins
ch ap te r 6
In This Chapter
6.1 Introduction 6.3 Concept of
6.2 Exceptions and Exception Handling
Exception Handling 6.4 Exception Handling in Python
.1 Introduction
r natur ally. Sometimes, you misspell a
When you create and deve lop prog rams , error s occu
chan ge the symbols. These are very
name or k_eyword, or some time s you unkn owin gly
is not that easy and error s are not that
c?mmon and easy to hand le error s. But prog ramm ing
may occur, langu age deve loper s have
sunple. So, to handle virtu ally any type of error s that
. Pyth on also supp orts a specific and
created numerous ways to catch and prev ent them
error s of any type that may occur. This
well-de~ed mechanism of catch ing and prev entin g
chap ter you are goin g to learn abou t
mechanism is known as Exception Handling. In this
excepti h . of error s that may occur and ways to
. on andlmg techniques in Pyth on, diffe rent types
avoid them.
\
\
259
T
COMPUTER SCIENCE WITH
PYT1-toN ,
, IJI
t' n Handling
6.2 Exceptions and Excep 10 -- - • •
~ ~:.l~~ ~~~::::_::.:..::.L-- - - . d 'ctory or unexpected situation or in shot
. . to some cont1 a t r ' an e
Exception, in general, retet s d velopment, there may be some cases '"h rror
.· program e •v ere
that is unexpected. DUI mg . t that this code-fragment
l e the certain y
I
EXC EPTIO N
the
programmer does not ,av ·t cesses to resources that
. I1t either because I ac Contradictory or U
is going to ,-vork ng , f unexpected range, etc. ·t . nexpeClfd
it gets out o an s, uat,on or unexp
do not exist or b ecause erally called exceptions during program ex
ected
err0r
TI1ese types of anomalous situations are gen - t· handling known as Exception.
ecutio .'
n, ~
and the way to hand letl1eir1 ts · called
- excep 1011 ·
try:
#wr ite here the code that may gene rate an exce
ptio n
exce pt:
#\o.Jrite code here abou t what to do when the
exce ptio n has occu rred
try :
0
.
0
n belo w:
resu lt of 10 / 5 = 2
resu lt of 10 / 0 = Divide by zero Erro r ! Deno
minator must not be zero !
See, the expression (10 / 0) raised exceptio11
which is then handl ed by excep t block
try:
x = int(" XII" )
exce pt:
prin t ("Er ror conv ertin g 'XII' to a number")
Con side r prog ram 6.1 that is expa nded vers ',
ion of the abov e exam ple. It erro r- check5 'a ttser .
inpu t to mak e sure an inte ger is ente red.
263
EPTION HAND LING
6 . EXC
Chapter .
and in case any other valu e is entered, it
Write a progra m to ensure that a n intege r is entere d as input
r,6.1 displa ys a messa ge - ' Not a valid intege r'
ok = False
Lrarn while not ok :
try:
numb erStri ng = input ("Ent er an integ er:")
n = int(n umbe rStrin g)
ok = True
excep t :
print ("Err or! Not a valid integ er.")
,~
[~
l~
owError
or
Raised when the result of an arithm etic opera tion is too
Raised when a mapp ing (dictio nary) kev is not found in
Raised when the modu le given with impor t statem ent is
large to be repres ented.
the set of existi ng kevs
not found .
t eyboard/nterrupt am execu tion and norm al
Raised when keys Esc, Del or Ctrl+C is presse d durin g progr I
progr am flow gets distur bed. --
264 COMPUTER SCIENCE
WITH PYTL,
•1()N
Following prog ram 6.2 hand les an error that may occu
r while open ing a file. ' 111
;r, 6.2 Progr am to handl e excep tion while openi ng a file.
try:
l~ram my_f ile = open ("my file. txt", "r")
prin t (my_ file.r ead( ))
exce pt:
prin t ("Err or open ing file" )
TI-l.e above prog ram will open the file succe ssful ly if
the file
myfile.txt exists and conta ins some data other wise it show Error opening fil e
s an
outp ut as:
The excep t clause can then use this addit ional argum ent
to print the associated error-messageol
this excep tion as: str (exA rgum ent). Follo wing code
illust rates it :
try:
prin t ("res ult of 10/5 = ", (10/ 5))
print ("res ult of l0/0 = ", ( 10/0 )) Notice second argument to except block i.e., e
excep t ZeroDi visio nErr or as e : ~ here - gets
referen ce of raised exception
print ("Exc eptio n - ", str( e)) ,.___ __ Printing standa rd error message of raised
exception throug h the second argument
The above code will give outp ut as :
res ul t of 10/5 = 2. 0
Exce ption - di visio n by zero ~ The m essage associated with the ex9eption
try:
#:
except<exce ptionNamel>
#:
except <exceptionNa me2> :
#: The except block without any exception name
except : will ha11dle the rest of the exceptions
#: ~ }
else: ~
#If there is no exception then the statements in this block get executed.
n1 e last else: clause will execute if there is no exception raised, so you may put your code that
you want to execute when no exceptions get raised. Following program 6.3 illustrates the same.
except ValueError:
print ("Could not convert data to an integer.")
6 .4 .5 Raising/Forcing an Exception
In Pytho n, you can use the raise keywo rd to raise/f orce an
except ion. That means, you as
progra mmer can force an excep tion to occur throug h raise keywo
rd. It can also pass a custom
messa ge to your except ion handli ng modul e. For examp le :
raise <exce ption> (<message>)
The excep tion raised in this way s~o~~d be a pre-de fined Built-i n
except ion. Consi der fol_lo~in~
code snippe t that forces a Zer0D1 v1szonE rror except ion to occur
witho ut actual ly div1d1ng'
value by zero :
26 7
. EXCEPT/O r i HAND LING
ci,apter 6 ·
Notice tl,i.~ raise state111e111 is raising
trY: h11ilt-i11 exceptio11 ZeroDivisionl:rror
a= int(i nput ("En ter num erato r:"))
111itl, a cus/0111 m<'ssage. that follow.~
b = int(i nput ("En ter deno mina tor:" )) the exception name
if b == 0 : 7 )
raise ZeroDivisi onE rror( str (a) + "/0 not possi ble"
prin t ( a/b) ·
excep t zero Divis ionE rror as e:
Print ("Ex
cepti on", str ( e ) ... ..
·.
••
..~
♦
print ("En ter the Deno mina tor: ") The assert keywo rd in Pytho n
- - - Tl~is error message will ?e is used when we need to
d = int ( inpu t ( ) ) ...--- printed only when the gwen
!= o results detect proble ms early.
asser t d ! = 0, "Den omin ator must not be 0" condition d
into false.
print ("n/d =", int(n /d))
Benefits of Exception Hand ling
of what
Exce ption prov ides the mean s to sepa rate the detai ls
ens from the
to do when some thing out of the ordin ary happ
ption
main logic of a progr am. In short , the adva ntage s of exce
:me th e block that encloses the code hand ling are :
at may encounter anomalous situations. from
2 (i) Exception hand ling separ ates error -hand ling code
· In Which block can you raise the
exception ? norm al code.
(ii) It clarifies the code and enha nces reada bility
.
3. Which block
traps and handl es an takes
exception ? (iii) It stimu lates cons eque nces as the error -han dling
4. Can one ex place at one place and in one mann er.
cept block suffic iently trap
anct h
5. Wh·
andle mutt'1P1e excep tions ?
(iv) It make s for clear , robus t, ._r.N ~~~- -- -.J
lch block · fault -tole rant prog rams . O T E
tnatter wh· h is always execu ted no
ic exception is raised ? All exceptions are sub-cl asses
.....___
6. Narn
e the root l of Exception class .
c ass for all excep tions.
268 COMPUTER SCIENCE WITH p
YTHON
' Xii
❖ • • ·
Way of handling anomalous s1tuat 1ons III a progr•am ·run is known as exception handling.
❖ The try block is for enclosing the code wherein excep
tions can take place.
❖ The except block traps the exception and
handles it.
❖ The raise keyword forces an excep
tion.
❖ All exceptions are subclasses of Excep
tion class.
' -
OBJECTIVE TYPE QUESTIONS - .· . . '.- · OTQs .
MUL TIPL E CHO ICE QUE STIO NS
I. Erro rs resul ting out of viola tion of prog
ramm ing lang uage' s gram mar rules are know n a s _ .
(a) Com pile time error · (b) Logi cal erro r
(c) Runt ime error
(d) Exce ption
2. An unex pect ed even t that occu rs duri ng runti
me and caus es prog ram disru ption , is called _
_
(a) Com pile time error
(b) Logi cal erro r
(c) Runt ime error
(d) Exce ption
3. Whi ch of the follo wing keyw ords are not
specific to exce ption hand ling ?
(a) try (b) exce pt (c) final ly (d) else
4. Whi ch of the follo wing bloc ks is a 'mus t-exe
cute' bloc k?
(a) try (b) exce pt (c) final ly (d) else
5. Whic h keyw ord is used to force an exce
ption ?
(a) try (b) exce pt (c) raise (d) final ly
FILL IN THE BLANKS
I. __ _ exce ption is raise d whe n inpu
t( ) hits an EOF with out read ing any data .
2. __ _ exce ption whe n a local or
glob al nam e is not foun,d .
3. __ _ exce ption is raise d whe
n an oper ation is appl ied_.to an obje ct of wron
g type.
4. Whe n deno mina tor of a divis ion expr essio
n is zero, __ _ exce ption is raise d.
5. Whil e acce ssing a dicti onar y, if the give
n key is not foun d, __ _ exce ption is raise
d.
6. The code whic h migh t raise an exce ption
is kept in __ _ block .
1REcr10NS . . .
D 11 t/ie following ques!wn, a statement of assert10n ( A) ,s followed by a staf-c1nent of reason ( R).
I correct ckoice as :
},tfark t1ie .
(a) Both A and R are true and R _1s the correct expla nation of A.
(b) Both A and R are true but R 1s not the correct explanation of A.
(c) A is true but R is false (or partly true).
(d) A is false (or partly true) but R is true.
(e) Both A and R are false or not fully true.
Assertion. Exception handling is responsible for handling anomalous situations during the
1.
execution of a program.
Reason. Exception handling handles all types of errors and exceptions.
Assertion. Exception handling code is separate from normal code.
2.
Reason. Program logic is different while exception handling code uses specific keywords to handle
exceptions.
_ Assertion. Exception handling code is clear and block based in Python.
3
Reason. The code where unexpected runtime exception may occur is separate from the code where
the action takes place when an exception occurs.
4. Assertion. No matter what exception occurs, you can always make sure that some common action
takes place for all types of exceptions.
Reason. The finally block contains the code that must execute.
NOTE : Answers for OTQs a re given .at t h_e end of the book.
~olve~ Proble~ cl
L,. eeo
l. What is an Exception ?
Solution. Exception in general refers to some contradictory or unusual situation which can be
encountered while executing a program.
2
· When is Exception Handling required ?
Solution. The exception handling is ideal for :
♦
processing exceptional situations
• processing exceptions for components that cannot handle them directly
• processing exceptions for widely used components that should not process their own
exceptions
·
• large proJects ·
that require uniform error-processing.
3. What is the function of except block in exception handling ? Where does it appear in a pro~ra111 ?
I di . J
Solution · An except: block is a group of Python statements th at are u sed to 1an e a rrusecl exce ption.
•
Th
e except: blocks should be placed after each try: block.
270 COMPUTER SCIENCE WITH
PYTHo~,
- ~I
6. \,vJwt is tl,e output produced by following code, if the input given is : (a) 6 (b) 0 (c) 6.7 (d) "a"
try:
x = float ( input ( "Your number:" ))
inverse= 1 . 0/x
except ValueErr or:
print ("You should have given either an int or a float")
exceptZe roDivisi onError:
print ("Infinit y")
finally:
print ("There may or may not have been an exceptio n . ")
Solution.
(a) There may or may not have been an exception.
(b) Infinity
There may or may not have been an exception.
(c) There may or may not have been an exception.
(d) You should have given either an int or a float
There may or may not have been an exception.
7. Whllt is the purpose of the finally clause of a try-catch-finally statement ?
Solution. The finally clause is used to provide the capability to execute code no matter whether or not
an exception is thrown or caught.
8. Identify the type of exception for the codes and inputs given below :
(a) #input as "K"
(b) for a in range(0, 9):
x = int(inpu t( "Please enter a number:" )) print(20 /a)
(c) import mymodule
(d) x=8
(e) mylist = [2, 3, 4]
print(X)
print(m ylist [4])
(j) import math
(g) filename = "great.tx t"
a= math.pow (100000, 100000) open("gr aet . txt" , "r")
Solution. (a) ValueError (b) ZeroDivisionError
(c) ImportEr ror (d) NameError
(e) IndexError (j) OverflowError (g) IOError
271
~ . EXCEPTION HAN DLIN G
chapter .
ion calls:
predict the output of the following code for t/1esc funct
(b) divid e(2, 0) (c) divid e("2 ", "1")
9. (a) divid e(2, 1)
Solut ion.
resu lt is 2
(a) divide(2, 1)
exec utin g fina lly clau se
If CE.I< I ■♦.J
.·_.->~
'1
NCERT Ch t 1 ption rlan dl,:t-,g in Pxth I
on ' '
9· W/1 f . th
J\n n is e use of finally clause ? Use finally clause in the proble111 given i11 Questio11 No. 7.
s. Refer to section 6.4.4.
COMPUTER SCIENCE WITH
PYTHON .
, l)j
GLO SSA RY
I X f@wtlr1fte'tif'lt¥ffll m zxrv 7
1. What is except ion ? What is except ion handli ng .?
2. Why is except ion handli ng necess ary ?
3. How do you raise an exception? Give code examp le.
4. Hmv do you handle an except ion in Python ?
5. Descri be the keywo rd try. Whaf is the role of try block?
6. Predic t the output by follow ing code :
impor t math
def f(x):
if X <= 0:
raise Value Error( 'f: argum ent
must be great er than zero')
return math. sqrt(x )+2
def g(x):
y = f(x)
print (y > 2)
try:
g(l)
g(-1)
excep t Excep tion, e:
print 'Excep tion', e. messa ge
7. Which of the follow ing two codes will print "File does not exist"
if the file being opened does not exi 5t ?
(a) if filena me ! = " ": (b) try:
f = open( filena me, 'r')
f = open( filena me, 'r')
else:
excep t IOE.r ror:
print ("file does not exist" )
print ("file does not exi 5t ")
8. Which of the follow ing four output s is produc ed by the code
that follow s ?
outpu t 1: output 2:
-2 -1 -2 -1
-1 -1 -1 -1
o integ er divisi on or modulo by zero 0 integ er divisi on or modulo by zero
1 1
2 0
. EXCEPTION HANDLING 275
6
cnopfe( .
output 4:
output 3 :
-2 -2 -1
-0. 5 -1 -1 -1
-1.0 0 0 Exceptio n occurred
division by zero
1
1.0 2
o.s
Given code is :
forxinr ange(-2 , 3)
print (x, sep =" "),
try:
print ( 1/x, end = " ")
except ZeroDiv isionErr or as e :
print (str(e) )
except :
print ("Excep tion occurred ")
9. Find the errors in following code fragment s :
(a) try:
fs = open("/n otthere" )
exceptio n IOError :
print ("The file does not exist, exiting graceful ly")
print ("This line will always print")
(b) try:
fh = open ( "abc . txt")
try:
fhl = open("ne wl. txt", "r")
except ValueEr ror:
print ("The file does not exist, exiting graceful ly")
(c) def ret() :
sqrs = [ x**2 for x ~n range(l, 10) ]
i=0
while True :
return sqrs ( i]
i += 1
c = ret () . next ()
10, W.
rite a f . ed error if values
other th unction read a Time class obJ'ect storing hours and minutes. Raise a user-defin
lJ · Write an O..23 is ·
· entered for hours and other than 0 ..59 is entered for mmutes.
excepti~ rogram to read d e tails of student for result preparatio n. Incorpora
te a ll poss ibk-
s
etc. n- ao<lling codes such as ValueErro r, IndexError, ZeroDivis ionError, user-defin ed exception