Exception Handling
Exception Handling
\ I,
. .
,1 ,,1 , "t•pt,011- ll;111dliluru
..,_ ..0 tCL· - -
cJ ..... ,TI ,,f 1•1n,1 -h,111111i111'' Is l'll'II )' •i n11•lr • II
, .... •~1,•l"I ,,,11, .
111
. ,.,.
11<, w 111,, I .11 1 , •uh•,,,,,•/
11 , , 11\ ,.
"'"'"'' "J
,~f'll!J
l I
die error. And surrounding a l)O~S¥n0<19
t;:Jtt.h r,'. (t..Cf,V '~
'
'Vor; -
Ur.handltd uttptl ani will caustt Pylhon 10 hall c•ecutlon.
\ 1')' •
·
lh<ri te here t he code t hat DiYgenera tc an exception
exce11t :
llwritc code here about what to do when t he exception h.is occurred
See, now the output produced does nol show the scary red-coloured standard error m=ge
; ii
is now showing what you defined under lhe exception block.
Consider another code that handles an exception raised when a code tries conversion from texl
to a number :
t ry:
X• int("XII")
except :
print ("Error converting 'XU t o a nu,r.ber")
The output generated from above code is not U1c usu Ill error now, ii is:
r
Error converting ' XII' to a number
Consider program E.1 thJt is expanded version of U1e Jbove ex.imple. It error- diccl:s J user's
input lo make sure an integer fs entered.
I
£ntcr, Not a valid integer.
error an integer: 007
cntcr
Generol Buill-in Pylhon Exceplions
f .tl this sccllon,
· we are d's ' b ·1 .
I cussrng a_ out some built-in exceptions of Python. The bu~ t-~n
511
,eXccptions can be generated by the rnterprctcr or built-in functions. Some common built-in
~ccptions in Python are being listed below in Table E.1.
Table E.i Some bvilt-in Exceptions
10 Error Raised when an 1/0 operation (such as a print statement the built-in open( ) function
or a method of a file object) fails for an 1/O,related reason,, ,.g.. "file not found" or "disk
full".
N1111c£rror Raised w~en a local ~r global nmc is not found. This appliC?S only 10 unqunlified names.
The assooated value IS an error messa.c that indudcs the name lhnt could nol be round.
Inda.Error Ra~d when a seq11ence subscript is out of range, e.g., from a list of length 4 if you try
to read a value or index like 8 or -8 etc. (Slice indices are silently truncated to foll in the
allowed ran2e ; if an index is not a clain inle~cr, Turu•Error is r,1iscd.l
/mpMIError Raised when an import statement fails lo lind the module de!inition or when a Iron, ...
imoort foils to find a name that is lo be imMrted.
'Typtf:rtor Rni1cd when an operation or full<!tion is applied lo an object or lnopproprfate type. (.g.,
if you try lo comptlle a square-root of a slrin& ,,aluc. Tile nssociated value is n string
civin~ details abou l the tvoc mismatch.
Vol11tE.rror Raised when n built-in Op<?mtion or lunction recciws a.n argument lhnt has the right
type bul on inappropriate value, and the siltmlion is 11C1t described by n mo«• pr~cise
cxccnlion such ns /Jldcx£rror.
uroDivi5io11Error Raised when the second nrm•ntent of n division or modulo OL>er,1Hon is zero.
01,aflowError Raised when tho rl!Sull or nn nrilhmclle orn.•r,,tion is too IM•'< lo be ro•>~s..•nled.
l:,ufrro, Roiscd when n mannin" rdlclionarvl ke\' is not found tn lhc s.,t of cxistine kc1·s
l,000,1r.rro, Rnlsed when the module "iven with lmnnrt stntcnwnl is nol found.
K,yt,oard/11trrr11pl Rniscd when keys Esc, Del or Clrl+C Is pressed during 1'1U~r.1n1 excC111ion and num1JI
orogrnm flow ~els disturbed.
L
Qi Scanned with OKEN scanner
I t 1/,\PI JI I P '•' II 111 I '111111 1•1111, 11 1
A. \8 '"
vhll•• 111 ,.,11111/', 11 lllr
.
l,1111'1\ II\)\ pnI ).I.Ill\
• I' ) Il,llllll1• 1 ,1111•111 ,r II111 I II I •,,. flt "II I
I I'~•:
11\)•_fl I~ • npcn("myfl \ o, ld", •r")
1w1,,1 (my_filc.rond())
c~ccpt :
print ("Error 011e111nu file")
TIil' ,,bow l'"'fitam will open the file succcssf11ll)1 if ihc file 0 error OflCning file
"'.¼/i/l'.1.1·1t.!:l.isls nnd nmlnlns some d11tn othcrwl~c ii ~hows nn
011lp11l ns :
Now the ntio,·c output mny tic of one of the 11110 reasons : .
. .. no dota In the file.
(1) tl,c file d1d nol e~isl or (11) there wos
Dul the above code did nol lcll which cnuscd U1c error.
The except cli111sc can then use this additional argument to print t~e associated error-message or
this exception as : str (exArgumcnt). Following code ill uslTatcs it :
try:
print ("resul t of 18/5 = ", (18/5))
pr int ("result of 18/8 =", (18/ 8)) No1krs«001d o,g1,mr11/ 10 =,,pt bloc!: i.r.• ,
__,,,. l«w - gel< refmmrt of raiml t'lWpliOft
except ZeroOivisionError as e : -
pri nt ("Exception - ", str( e) ) ..___,,- Pti111i11R ,t11ndanl error no=g•· of roisrtl
r.creptlo11 tl1rot"'' Ilic SfflJJ/J '"ll-""',''
The above code will give output as :
result ,of 10/S c Z.O __,,; 11,a "''""t' •=imrd uo/1/1 //or e1wp1io11
Excepti on - division by zero -
,<11-1)1,X ~}
~ h ilW ,IS 1wr follnwl1111 f11nnoi .
'f11l~ IS I •
trY:
II :
t <cxccplionNamo1> :
0xcoP \
d:
t <cxcept ionNom!!2> :
o~'Cp
p:
excePt •
. ◄
#: A("}
eise : 1/f./Jf'
ff If there i s no exception t he th
n e state:r,
. ;ents in this bl
.,.,,,c tasl rise: dausc will execute if th . O<:~ get; eY.ewted
1,. 1 ere 1s no ex . ·
,ou want to C>.'(!Cllle w ,en no exceptions . cepbon raised ,
> get ralS<?d, Follow· ' so } oU may put your code that
r, £.3 : :mto handle multiple excepllons.
mg progra E .
m .J illustrates lhesame.
i I/ 0 error occurred
L
111111n111etl cxa71I suite is ext•cutcd.
Irv :
N •,l,"""'r nl •· th,, I n,1y l'nl~•• 1•x1 c>pl lull
Ii'\ C('jll :
• h,,ndlr ('- •l'tll Ion h ~l'C J
f! Mll y:
H latl'mr11ts tlml1dll Jlw,1ysrun ,. II !JI ,.
block ir. lhnl I1IC 111,1 y: t1<:r. i~ a pl'
111<' dlff,•MI~ 111.•IWl"l'n an rxcl'pl: block and 1hr flua II )~, fry• •L,1•orr.
,. ·,,.d ~11 ' 'X'CJ>t·11
r,,r= • , , m or "'
' <•·
1h,1t ~"nl,1in~ •"')' rod<' lh~I musl cxcrulc, whclhN t IC I ' ~.
for cxnmplc,
try:
fh • opcn("pocms. txt•, "N-") 11,11 ""''"'"'" •"' • 1"'")' tir
fh,1,,-ite( "Adding new line") ,.aa,,td In ihaml
finally: . /l
print ("Error: can\'t find file or read data") (l(./JI'
. · I blnnlion the cxcepl:d block will g 1
You may combinc finally: with except douse. In sue 1 a com · ' ALW c
executed only in case an exception is raised and finally:•block will get execute AY S , in
the end. Following code illustrates it :
try:
fh =open ("poeml. t,ct•, "r")
print (fh.read())
except:
print ("Exception Occurred")
finally :
print ("Finally saying goodbye.")
0• ,~...
cm~ a"'1~1~fiG~-~~.-;;;--::rr.~..----=::.71 oTQ.s l'::i
MULTIPL[ CII OIC[ Ql/rs r ro,H,
, · , f•111,.Pu~&t"~ gramm,11ru""'- Ml' it,y," " ••·
•
, l'rrw'- n•,ult•"fl " "' oh ·lulJlh mII1procrn mn11n1,
Id (i,n\J'lk lim.- ~rror (b) Logic.ii error
A.23
f#'
s -
cc110N . ~ ,,11rstfn11, II Mnlc111rul of n!ml/011 U)
0tR rllr'1·,111,111•"'• • •ns . Is /ullo1utd b
\
rlrorcc:
i,1fl'l'(I • Ya SIQlrmmt of ,e11So11 (R).
111
~W~ tli< th A "nd R MC trnc ond R is the correct
' (~) 11\ /I and R m'\' true liul ll is not lhe CXplnnnUon ol /\.
N 110 '
( ) /I is tnie l>ul R IRfalse (or porlly true). C'Offcel cxnt
,. •nation ol /\, '
I' A I• folSC (or p3rtly true) but R Is true
(ii} . • • . (c) Both t, d
·on, Ext'l!phon hnndllng 1s rcsponsibl an Rare false or not fully true,
Ac..¢ rl 1
1. ~ t1on of II progron,. . c- for hand I'
1 ing anomalous situations during the
c~ ~"· 6,x{'Cption handling ho.ndles o.11 types of
Rt- . . errors and ex .
..,,.rt,on, Exception handlmg code is scpa
2 ,.,,,,.. ra 1e nom norm cepuons.
<-
· Rc,'1 5011• Program logic is di{ferent while exl"eption han . aI code.
cxcel'tions. dling code uses spoofic keywords to handle
J. As¢1ion. Exception handling code is crear and blodc based
.
"cason. The code where unexpected runtime 111
.
"
the action takes pare 1 h excephon may oc Python .
. separa
w en an exception occurs. cur 1s te .from the code ~here
Assertion, No mo.tter what except occurs y
4• ta)(es place for all types of exception ions. ' ou can always make sure lh.lt some common action
Reason . The finally block contains the code that
. must execute.
ANSWERS
MCQs
J. (t) 2. (dJ 3. (d) 4. (cl S. (c)
Fill in the blanks
1. EOfErTor 2. N.imeError 3. TyptEnor 4· ZcroOivisionEn-or 5. Ke')'Enor 6. II)'
Tnie/Folse
J, False 2. F~bc 3, False ~- Trut! 5. True 6. True
Assertions/Reasons
1, (c) 2. (a) 3, (a) 4. (n)
L
0 Scanned with OKEN Scanner
A.?4
1i1.,,, ,/,
ti ,.,.,,,,,
.11
1,1 • ,,,,,.,,. ,., '
1 i i I" 1,,.,.,IJ, ; I AI ,.,J, ,,...,.
1\.,../ 11 /¥ fll,• 1~'" " " 1'rl /,/,~l Ill rh1/1~"f /14" flt~ f ,,..• , ,,, " ' ....., ••
" ,10 th•• " " "''''' ' hl11ii I h ' "''"'f'OI l'tl lt1 ♦tl , , ,,. "'' fl
11,r f\tl'('II l•I•~ ~, , l,, ~11,t I~• plA,,-, t ftfh I i'A• h h i fol,• I
111 I rf 1/•11,:,,,.,,_\'" of • l!?'fl/jl\n 1.,"4//NI I
try:
x c flo.t(input( 'Your lll.lllber:•))
invcrs11 • l.0/x
e,:c,ept Val~Error:
print ("You should have given either an int or a float")
ex~t ZtroDivisionError:
print ("Infinity")
finally:
print ('There may or aay not have been an exception.")
Solution.
(a) There may or may not ha~ been an exception.
(b) lnfiruty
There may or may not have been an ex<l!ption.
(c} ~mayor 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 ~ I is tht Pllrposc of lht finally do115~of a lry"<J1ld1•Ji1101/y slolmmll ?
So!utioa The finally clause is used to provide the capability to execute code no m~:-ter whelheror n-:>:
an exe2plion is thrown or caught.
; . ldt11tify tr.e type of acqtio11 for flit rodts a11d i11p11ts gi~11 btlo«• :
(a) #input as "K" (b) f-ora in range(e, 9):
x" int(input("P lease enter a ntlllber: ")) print (28/a)
,,.
, ' I/1'I t!i,· ,,1111•111 ,,[ 1111' (. 1//1111 1/11~ , ,,,It- [, 11 1/im•J,
"' •
II
1111 1111 en/I•·
n) ,llvhh•(2, I l (/1) ,llvhlo•(2, 11) ( ) II ., .
I ' < Vluc("2", "I .. J
def o1vid<i(x, y):
tryr
r csul l • x/y
~xccpt Zerol>lvis!onError:
pri nt (''d i vision by lcrol")
else:
flf'int ("result ls" 1 result)
finally:
pri nt ("executing finally clause")
Sol11liC1n,
(n) dividc(2. 1) result is 2
executing finally clause
(h} divide(2. 0) division by zero!
executing finally clause
(c} di,'ide("2", "1")
executing finally clause
Traceback (most recent call last):
File" <pyshell#46> •, line 1, in <module>
divide("2", "l")
File "C:/testl6.py·, line 22, in divide
result" x/y
TypeError: unsupported operand type(s) for /, 'str' and 'str'
1 11111
r,r, 1,,11
tu:'''
~- ll'l-..11 •' l~.t l/5l ~~ • m~ f/a/(mtn/ , ll'rilr ' crdr 1
,~ ~-":vml n11111/l(T (1/c11nmi11alilr/ •• '"u
· . ,,A •xl'cptim1-~ nrc rJiscJ by f•yu~~,
,vrn'l'rillr r, rq,11,,n .<Jtou1d /1< rni.:<d ,7 11,r 11w.mtC15 ccpllon 11,... c
• r,115(' • " ex
,\n<. TII<' raist krp,orJ is used to n,.munll)'
it<rll.
a =int( input("Enter value for a:•))
b = int( input("Enter value for b: •))
try:
if b e: = using raise keyword
raise ZeroOivisionerrori raising exception
print(a/b)
e:rcept ZeroOlvisionError:
print(. Please enter non-zero value for. .b,.") ion ill //re program.
test rht drolSI0 11 upress
4. USt llSSt11 srorancnt in Qut:S/ion No. 3 to
Ans. a clnt(input(·enter value for a : "))
b • int(i nput (•Enter value forb : · ))
assert b 1=8, •valueforbll!Stbenon•zero·
print(a/b)
,ing nn a«ption (c} Catd1i11g nrr cmplim,
S. Definl 1Jre Jolknlling : •J f.:taplion Handling (b) 17,rrm
Ans. (a) Refer Section EJ; (b) Rder Section E.5;
(c) Reier Section E.4
I 1xor1t()N lt~NOllNG
1.rl'fl\'Oi~
A.21
quot ient • (nllffil /nu~}
1,r1nt("Oot h the nu::ibers entered u~ere correct" )
cxc<'Pt ValueEr ror:
pdnt("Please enter only n1n1bers"} u to enter only lnteger-s
except ZeroOivisionError:
pr i nt( "t.'umber 2 should not be zero") • Denominator shouJd not be uiro
else:
print("Great . . you are a good prograll'rner")
finally: Rto be executed at the end
pri nt("JOS OVER ..• GO GET S<X-IE REST")
s. )'011 /illl't kanil how lo IISt ma/Ii modrrlt ;11 Class XI W .
10
arg11mcnt$ fer a 111tl/1od (say sqrt(} or p,JID( }). U!t 11,; " t , code "''.1m !JDu ,,sc tl,c 1or011g rrumbcr of
.
e.rc.:p I,on. • accpt,on lumd/111g pr«css to cntc/1 1/rc ValucError
Ans.
ic,port math
print ("Code to testWl'Ong TYPE of argu:rients")
try:
mn1 " int(input ( "Enter the first number"}}
resultl • math.sqrt(numl)
print ("Sqrt:·, resultl)
except ValueError: # to enter only integers
print ("Please enter only Positive nu~bers")
try:
m.1112 • int(input("Enter the second nu:iber"))
result2 =math . Jl0'<1(nU111, num2)
print ("Pa>n:·, result2)
except ValueError: l: to enter only integers
pr-int ("Please enter only m1nbers")
finally: # to be executed at the end
print("Tested only wrong types; Wrong no. of requires requires •args")
Code to test wrong TYPE of arguments
Enter the first number-9
Please enter only Positive numbers
Enter the second numberk
Please enter only numbers
Tested only wrong types; tirong no. of requires requires •orgs
Code to test wrong TYPE of argwients
Enter the first nultber6
Sqrt: 2.449489742783178
Enter the second number4
Po.•: 1296.0
• • "llS
Tested only wrong types; wrong no. of requires requires a, ,
• II . I' ,M.,,, "il\'tl in Qu,-:;ti,111 N,,. 7.
9. Wl,nt is the 11~ of fi11nlly clnuk ? Us.- f,11111I!I (Inus,· m " 1' · ' .~
Ans. Refor lo section E4.4.
L
0 Scanned with OKEN Scanner
coiAl~ llf P ~rn r 1r.r V/1111 r• r111r, 11 ,.
11.28
G1.o_~
L 11,,1 flfOll'um
A11 oomno1ovt \llunl1on r11c1Juntr,c, I Y
I\Tt'j!rl,l~ k, ,,ululfou """' ·
rn,gmmmlnp longuouo'i <1101nnw,, '" s Juli"9 comJll·Jal'nn
.l)"'ro, (ffllt • r,J
1
r"wwlr lfmt c"o,[11 011h01 1hr compflr.1/lnle1~1ah• con f,
~ l.nt trtOI (110, du1ing progmm OXQOJlion.
try:
g(l)
g(-1)
except Exception, e:
print'Exception', e.message
7. Which o( th, following lwo codes wiU print "file does not rxist'" if the file
being opened does not C'Cist?
(a) iffilen amel= "": (b) try:
IIIIIJIIII ~ I
11111p11I '
l J I
n., I I
I. (I 0 "I ~' ~Pllun nr, n,,~~
it\vl\ I 1111 h1• 1111 11
I
I. 0 >
o. ~
C.h•~n co1lr I~ :
for x ln r;innc( · ] , ) ) :
print (x, ~••11 • " "),
try :
prlnt (l/x, end . " ")
except ZcrolH vl slonError ilS O :
pri nt (s l r (e))
cxcer,t :
print ("Exception occurred")
9. Find the errors in following code fragments :
(n) t ry:
fs = open("/notthc!re")
exception IOError:
print ("The file does not eY.ht, exiting gracefully")
print ("This line wi ll always print")
(b) try:
f h = open("abc. txt")
try:
fhl = open("newt. txt", "r")
except ValueError:
print ("The file does not exist , exiting gNcef ully")
(c) def ret() :
sqrs = ( xnz f or x i n range(l, 10))
i =0
while True :
return sqrs [ i )
i ◄= l
c = ret() .next()
10. Write II function read n ·nmc class object &torl11g hou1·s and minull'S. l!niw a uwr•defhwd Nr~r if 1·.alue;
oUu:r thon 0..23 b entered for hours and utlwr than 0..59 is cnle1,·d for mlnull'S.
11. Writt II program 10 rcilll dclails of shnlcnl for l'l·suli pr,'p.iJation. Incorporate JII pcH6ible
cxccption-handlin1, codes 611ch a&V,,luoliiror, lmlexErmr, Z1•r0Ulvisi1111l:rrur. u,cr-<kf11w,J r\Ceptmns
Cle,