0% found this document useful (0 votes)
63 views16 pages

Exception Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views16 pages

Exception Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

/\ .

\ I,

l .' l \, q i\1111'~ ,Ill \\ l


\1 ''\1\\011 l l;i1ul11 11l'
I''''1
\h. ''"'\U\
,\ '" " 1'\Ill ~•·1' 1l,11• \l , u•l,
•i, \u ""' " ' ' ' i u11h 1>
,1l11 hH )' llf \lt\f''f1'•'1 l1·11
I' h ,I 11111 hw '1Hu ,,1i1 ,11 , 11 Ill'• J,111
' " " ' 11\\1111•1 1, 1111 i,,, ,,r
1.~. 11
' ' ' 11111 h" II 1' '1', • 111 ,,,.,·,•l11p1111•11I, 1111•11· II••• )' II(. •IHIIJI' • .,· •·
\
,. • ,. 1 1 wl,,.,,. II
1, '-" " ' )\ 11, "'''I. 11 tlll\. • •· "
,
,i,, 111,1 l'' " ' 1 •
d\h "' \\' 11 ,1\n t \'
l•i\ .. .
lhnl lhi•, n•h••h ,11:111 rnl
, ,.,11 .... ,1 .11 ,1••·•·• t11 1r•.1•11
Il.1r.1r11 011
1111~ I\,,~
~ \
' 11 ' " ,111
,! 1~11 I
,11 ii ~,.,,
" 11111 " I nn 1111e~p 1•11c il 1.111
\\" ' ' '-'"~'-II I'
11 l"' lh.11
11r, d r. loo1 rild1c1or•1
1;1 IJrv ' VU<•
·'" 'I I1,,. \\',I \' \,I h n11,u , \I 11,1 11111, ,111' 1't '111•1,1lly rnllccl <',rc1•llo i,1u,1,1m ur urtc, p•tl"d N, •
, ' n, 01
c 11' 111 1~ ,·,,lh-1l t•\ fq1tl1111 hnnJlln t\· du11 ng p1~fldtn lt' ";'.rtkJri ;
1'1\,1,ll,· tlw l\' •'~ la, , h1- loo m, ,..., l •<-~llon.
J
I ' '
" ~ \l l1 llU I ~ :
(1) Co1111•ili'-li 111r r,
l~"t:."~!\C,~ · Wi .
s. 111cs11 ,\I'(' lhc errors . .
rcsullinr out ol vio
• "•' rnm
' m ~r ni Ics I'.): . wrltln~ syn '
l~h on of pro irarnm ,n
pr \nt (. ,,.. ,, ) lactic~lly lncnrr l'<t <latcmt'TII like i\
2 :
,,;\I
l\':<\l\t into
. cornp,·1l!·l)'Jll! error l>ccaus • nhd • ~yntnx All
1\-port,'I\ durmg complla c ol mv . ~yntai crro" •re
lion.
(ir) Rrm•limc ftrors. 11,c
erro111 that occur during runllm
Sudi ~rro~ nrc handled thr c bi:cause of unexpected situ•tio
oug h exc ept n...
handling 15 a transparent and ion han dling routines of Pyt hon . Exc
nice way lo handle program ep1 ion
Mal\y rca.wns support the use errors.
h:mdling arc : ol cxc cplion han dling. In other words, advilJllages of cxe
eption
lr) Exceplion handling sep
arates error-handling code fro
(ir) It clarifies the code (by m normal code.
removing error-handling cod
enhances readability. e from main line of program) and
(ii,) It stimulates consequen
res as the error-handling tak
m11111er. es place at one place a."ld in one
(iv) II makes for dear, robust
, fDult-tolcrant programs.
So we can summarize Excep
tion os :
h 11 an exceplional even, ~1a1 oc
= during runtime and causes norm
al program Oow 10 bedisrup1td.
So me common examples ol
£xccplion s are :
c) Oivide by zero errors
◊ Acassing the clements
of an array beyond its range
c) Invalid Input
e) Hard disk crash
c) O~ nin g a non-exis ten
t Hie I h CEPTIOI< H ANO llNG
◊ Heap memory exh~usied W~ of tw>drilli: aoo m:ilM
sllu.1\lo:u b > prOl f'!M \I'\ l,
Fo r instance, ronsldcr the [oll
owing rode : ~nown •~ u:tt pllon Hand~O
&
»> pri nt (3/ 8)
If yo u execute al>ovc cod,•,
i•ou'II receive a11 ~rtor mess.,ge
.is ;
Traceback (MOst recent ol
l las l) :
Fl le "<p~shclllO> • , line 1,
In (tllOdulc,
pri nt 3/8
1troOlvl sl onCrror : Inter.e
r div isi on or IIIOdulo by zer
o

0 Scann ed with OKEN Scan ner


- -
rr 4, I I
fl I '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\ ,.

1 ' ·1•1)"1·1111t• ~umt~I I' II r1·1



4',,111111•1•111,rl,11·('1 11111~1 ~1..,-i;w runJ~ 'lhc•ol r.•iolhl1. rrr,,r ,tJ~,rn
,:, ~t 1t ,,11 · wl> ' 1
lw ~mn••
th•'.~ ~,,,u,,I. II;''
,-.,ti 1'.'.l\lr ~l,\llltlin1: 111111h1r. TI1~ i11h-11drcl fllO)\l olllt Oow r-l11,11ld

hi..•· th,· ,mr !'111•w11 m hg. E.1.


,. . •i<in~ <'f i111J1 •ino"'•
1••"' 1•1 • .. "

,r n~.: ;~ ,·,1llc.t lhrowi ng ri [i j --


('IT\
()I
"-
rAi~inS ~n error. When ,,n
cm>r i~ 1hro1,,,. lhr 01-crall
"~~n, ~~ponds by <'o1lching
V/1~0 eodo
AldllhalM
rolscs on
enor,lbtJ over,
limo somolhilg
f"2
II'"°' n>?
h r,•lt<l ll,cn
.
(, • l
1/"o
£nr,t•

"'"'"'' "J
,~f'll!J
l I
die error. And surrounding a l)O~S¥n0<19
t;:Jtt.h r,'. (t..Cf,V '~
'

b!od- oi error-sensili1·e- ""°" ..~


C\~e-1<ith-o:ceptio1,-handling
'• called trying to execule a figure E.1 CAin~pt or u,epllon hdndli ~g.
~!od: .
5ome terminology used within exception handling follows.
P thon TIU'l'11nolo

AA un eel error that occurs durin runtime


A set of code that mi ht have an exce lion thrown in it
d Throwing or raising an error
The process by which an exception is generated and pnsse
to the ro m.
upruring an exception th.it Im just occurred and execu
ting Catching I
StZlements that to resolve the roblem
dnm:.· or m,•p1laCY)• li~11
rne block of code that attempts to deal with the exception ,·xr.111
1,/ock ralr/1~/o_,~•,~·.l'- ---- -
or
(i.e.. roblem.
The stquence of method calls that brought contro
l lo the Stack trace
tion occurred. --
·
--'r=--~ .:.:.:.::.:....::.;;;...:==:~.:..:.;.-- --- --- ---- -'- --· ---
nn;nt where the excep

When to Use Exceplion Hondling


The exception handling is ide.il for: An l,~pticn cJn ~ gcn-.'I J:ew
b\' .,n Nro: in ,·our proStJm, or
<) processing cxccpliona l sihrnlions.
r,p"-.,tl\· \ to a rait~ stJttm ~t
<> processing cxccp lions for componcnls llrnt l-;,1111111 h,mdll'
them dircclly.
<> large projecls 1hnl require uniform cm1r-prt11'\'$Sin1t•

'Vor; -
Ur.handltd uttptl ani will caustt Pylhon 10 hall c•ecutlon.

( )) Scanned with OKEN Scanner


I f tMJ'I IIU \ ' 11 11( 1 Ynll t l' lfl l(Hi
A.16 ,,
[ 4 txCl't)lion 1t.111dllng In l')'lhon , II
:..... - · - - - I •rc11I r1~11~,.., 111 "' I"IIuwi,,., I
1, ,,•rh•"' 11,11"111111: in l'i•1h11n nm •h .,, 1111•""' 1 ,1 II)' ,1111 r, ,, "'"'
, lllrll h• 1lw h y blurk .u1d Ilic cot1 , ~,
'
I lh,11 llli\l' 1:1•1wr.111• ,111 1 \I
wli1•n•1n 1h1• ,,111• -r1•1lc111 ,~ ,, r 11 ,. , r,,,
. 111 ,11 In 1•x11•pl I r>Cr..
I
h.m,lln\f. "''"plr1111 wlw11 1lw r,n•1•1h•t1 s r.1 ~, 1• I ' I 1, ,,,, I

\ 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

For insi.,ncc, consider the lollowing code :


try:

print ("result of 18/5 • · , (18/5))


~ - Tit< eodr r1uit N'JTJ rvut ,,,
print ("result of 18/8: ", (10/8)) ~ _,.;o,,ht mctmitl t,yHod

Thi> ucxrt;,io, except :


ltlxk ; 1hit • W
=:rirl- n th< ..!~
o:rr,n,,r is r-h<d ~ " ' print("Di videbyZero Errorl 0tnocunatormust not bezero .I")
.
······ ···· ··· ··· ········· .
The output produced by above code is is shown below :
-
l result of 10 / S • 2
result of 10 / 0 : Di vi de by zero Error! oeno:,rina tor ,r:ust not he zerol
.....___ Stt. tht <TJ"f"i•• //0 IOI mual ,...,..,.
ul,/c/1 i1tlim /,.mlt«J 11)' r,« pl blotk

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.

0 Scanned with OKEN Sca nner


A.17
no1trnrn 1o 1•111111r thnt nn t111rnr1 1, 1•11tl'fl'tl n-. 1,111111 nr 1 11
Wrllr o l ,n11c - 'Nol n vnlld ln1rn1•1' . II11n ca\r ""Y 111hrr vn1ur 1,. rnlrrP( •
,111111n)'~n 1111'!-
ok • f/l)SC
i,hiJcnol0k:
I r•y :
nuniborStrl.nr: • !nput("Ent•r ·n 1
' " ntcccr·")
n n lnt(numbcr•Slrlnc) '
ok a True
except:
print ("Err:"orl Noto valid integer.")
an integer: 007

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

- Etceotlon Name Descri111ion


-
EOF'E.rror
Raised when one of the built,in functions (input()) hi!$ an cnd,of-lilc condition (EOF)
without reading any dnta. (NOTE. the file.read() and lile.rcadline( ) methods relum an
emntu slriM when thev hit EOF.l

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

l'mj!f,1111 111 lwullr r\11·1111011 \l'hllr 1111r1111111 n flli•,

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.

E.4 .2 Se<:ond Argument of the except Block


.
You can also pro,~dc a second argument (or the cxccp1 block' which gives a reference to lhc
exception object. You can do ii in following format :
try:
# code
except <ExceptionName>as <exArgument> :
# handl e error here

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 -

E.4.3 Hondling Multiple Errors


Multiple types of crmrs nmy be captured and processed diHerenlly. II can be usefi.11 to prol'ide a
more exact error message lo the user than a simple "mr error J,ns oecum:rl." In order to capture
and process different type of exceptions, there musl be multiple exception blocks - each one
pertaining to dlfforcnl typC! of exception.

- Qi Scanned with OKEN Scanner


( • IXclr110N 1IANlJllllG I

,<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~ my_f~le =open("myfile. txt")


my_hne =. my_file.readline()
my_int = 1nt(s .stri p())
ll'o/_calculated value ,. 101 / .
- my_1nt
except IOError:
print ("I/0 error occurred")
11,,.,
tlu,, ,,,,,,. 'I • 'II
ha,::J.tt IO ,,. ~ DC~ UT colCh ur.J
.,_ · . . Error• lalwErrorcnd
...,.,o,.,.;on'- .
r.rror Cn"p:'!or..s rc,prrtitv~·
except ValueError:
print ("Could not convert dat a toa . t
n l!1 eger.")
except ZerOOivisionError: .,__ _ _ __ _ _
print ("Oivisi on by zero error")
except:
pri nt ("Unexpected error:") ,.______ •=P'
Tit, IDfr!.Jr.-~J i 1«k ,.i!J
else: lu..,..d_k rJ-.e Mr of lr.t Gtt'tpt1'cm

print ("Hurray! No exceptions I") - - .


Tltu UJI ti,;: ~l,ct ,ri// flS CJl.'(!JJ('(/
The output produced by above code is: if,)J) arq,ti.,,is ,.uud

i I/ 0 error occurred

Exceplion Handling - execulion order


The <try suite> is executed first ;
Th• nlm•d ex~pl; blod> hand!•
if, during the cou rse of executing the <try suilc>, an lho nJmod exceptions while the
exception is rnised thnt is not handlccl otherwise, and unnomed e,cepl: block hJndles
all othc• u ceptions - ex~plions
the <except suite> is executed, with <nnmc> bound lo the
not n10nlfoncd In namtd except:
exception, If found ; if no mntd,ing except suite i~ found then blocks.

L
111111n111etl cxa71I suite is ext•cutcd.

0 Scanned wit h OKEN Scanner


, ,1 ,.,,,,11 , '·' 11 11r r 1'111111•11w 111 ,,,
A.20

d ,I 111<' l,11.111\' 111,., I ,. w,· •••«•pl· ltl,,. ~


,1, I jll'•l II••· VII 11 • • ~, :I. •. ,,
\ ,111 ,·.111 ,1l1111 1• • ,I fin ,11 \' h!,11 ~ 11l1111rt wllh ,1 It I' rH •

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.")

The output produced by above code will be :


• • 71,iJ iJ prin1td l,«Q,.,,,, ucrpc blod
TII/J is prilltcd 6«4= Exception occurred - - got OttUtcd ""''" arrpticn ocnum1.
Jinaffr- blod( to' flllfflltrd - - - . • l . db
in ihct"'1. Fina l y saying goo ye
In the above code if no exception is raised, still the above code will print :
Finally saying goodbye
because finally: block gels executed always in the end.
E.4.5 Raising/Forcing an Exception
In Python, you can use the raise keyword lo raise/force an exception. TI,at means, you as
programmer can force an exception to occur through raise keyword. It can also pass a custom
message to your exception handling module. For example :
raise <exception> (<message>)
The exception raised in Uusway should be a pr~defined Built-in exception. Consider following
code snippcl thal forces a Zcr0Divisio11£rror exception to occur without actually dividing a
value by 1.cro :

Q.: Scanned with OKEN Scanner


x'CtrllO N tcl\Nlll lNI \
!(lid (
,ti't~

r v :~ • Snl (lll l" 'I( , 11\ or n111


1
111w nl 01• : "))
\ 1111 ,ut ("l nlc w1 k11 Dfflln~l or :") )
t1• In (

11,.- \l\l ll'" ' l'''-"\\'~'--d hy Jll\ Wl ' C\l(\c


••
Is :
... '
)
~t tr nU1DCrator : 7
• •• •. • •. •
£nter deOOIQ!nator : 0
.,_,.,.,.ptio n 7 /0 not po ssi ble
/&' •~ • 1lro ,,m ,,,, • ,,.,,,,,,-,,irnnir ""'· fnt'IY
-f
C<"'-'- •• ,r,rri brruu1t '"' rmr,l1J1,
rt/ttr.ntt ll\JI ftt tnn f .,, t

1; <0,'I\C siNatiOOS. Y~ have a clear idea about lhe requ


..~ )W mow lhe liktly resu
irements and tesH:onditioru required
lis of somt conditions and whm resu . So in progra ms
cin aa$h Ille programs, you can use lts being diff ffl'll l from I l l e ~ rtSU
P)'lhon assen statement if lhe conditio lts
P)'lhon's uw t stattllltlll isa debugg n is resu lting as exp ec!M or not.
ing aid that tes1S a condition. II lhe con
your program just c o ~ to dition is tnJe, it does nothing a.-.d
ex~ te. But if the assen conditio
~n £r ro r excepuon With an n enluatcs to false, it ~ ~n
opuonal eJTOr message. The synlax
ass ert co nd itio n[, err or_messa of ass,rt sraiemwt in Pyihon. 15 ·
ge J .. ._ _ . .
For eiample, const"der the fouowm . g code:
print("Enter the Numerator: ")
Sp,a
mor
fr IN
,h""'JI• -_rnm
1 .a,,- - - ~

n s int ( inp ut O) - Custom fm>r rn,ssog,


-·- - - - sptri,'w
pri nt( •en ter the Denomi nator: 'N OT E -
")
. .
d • int ( inp ut ()) - - - n,u mot ....,.",.;ir 1>< Th• we rt k£'1WO•d in f'Vt),on
ass ert d !: 0, "Denominator mu primtd only a1,,., tht pm , is ustd when we nted to
st not bee • CO<tJilion d / 0 ormrtn d•1t e\ problcnu eariy.
pri nt( "n/ d ••, int (n/ d ) ) iJtro falsr.

Benefits of Exception Handling


Exception provides lhe means to
✓..1 to do when something oul of the
main logic of a program. In short.
separale lhe der.uls of wh at
ordina ry happens from ~he
L Name the bloclt that e11clo1cs th• the ad\·;m tages of exceptiol\
code handling are :
llllt may enalWlt el ano:nalous situation
s. (1) Exception h,wlling separat.-s
2. In which b\ot't can you nise error-hnndlli'& code from
lhe
u ception ? normol rode.
3. Which block traps and handles (it) It dnrifies the rode , nd en
an hM ~ readability.
euepllo n ? (iii) It stimulnlcs conscquenc,.-s
as the crro1~handlit\S t.lkcs
·• Cln one txctpl b\od: 1uffid
t111\y IRP pla ce at one pine{' .1ml 111 onl' ma
ui lwldte multiple exce ptions ? imer.
(iv) ll mot-cs !or clc,u. rob11st,
5. Which block u ahnys um1ttd
l!llt lft whld, uttp llon Is
tail ed ?
no foult-tolcrnnt progr,,ms. NOTE
(;,
All c,cep1tons arc sub•cl;uses
llt1J1t \111! too\ dw lot all o
ctptloM . of r,ci,p1ion <lass.

0 Scanned wit h OKEN Scanner


ff #JJtlt•fl ,I
, ., 'I"'"" J.,,r,,/11,,,,
,, , h.~~f l""•· 1~,,. ,,,,.n,,,,u ,.,,,,- .,"''"" '""
1 ffJf'ti ' ,,,, ,,,t' I /,r, I
f l\ii M f,11,,.. t n► 1
-,, j,,._,,111 ,I~ 1 Jtrff ti'"'"'"' tttf"
(' ,,. • ""' ~~- l ~ ~· ,,,. "" , "'"' "" " •' //, I ,,
~ 1 tt,ltt l n"4 ,t frtn'M Ott , ,, •rttlfl'1
I'')"'""' ,lrt••
,, , ,. ,,,,rt'.,,,,, \Hitt ""'f \ ,l(

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

(r) Rnl)linl<' m-ur (rl) l;xrcption


causes program disrup lion, 13 cal~
' An uOl'\l'"<tcd ~vcnl tl1JI ocn1rs du ring runtime and
(b) Logic.11error ----...,
(•) Compilr time CIT'Or
(rl Runlimc error (d} £xception
cltceplion handl ing ?
; Which of 1hr lollowiog keywords arc nol spt'Cific to
(/J} cxcepl (c} finally (d} else
(o) try
~ \\"hich of the lolloll'ing blocks is a 'musl-execu
lc' block ?
(c} finally (d} tlse
(~) iry (b) except
, Which keyll'ord is used lo force an exception ?
(b) except (c) raise (d} finally
(a) try

f ill IN THE BLANKS


ut reading any dati.
_ _ exception is raised when input( ) hils an EOF witho
l _ _ ciception when a local or global name is not
found.
object of wrong type.
• _ _ exctplion is raised when an operation is applied to an
exception is ~ -
4 When denominalor of a divisi on expression is zero, _ _
, _ _ exreprion is raise-cl.
S WhM accessing a dictionary, ii the given key is not found
block.
t Tot code which mighl raise an exception is kept in _ _

TR UE/FALSE QUESTI ONS

Exctprion and error arc lhc same.


2 All type5 of error~ ran be found during compile lim~.
l is an ex,'t'p tion.
) A progr•m running properly put producing wrong outpu
4 UOO!~ied m e t'Ondilion O<'curring du rins nmlim
c ll'hich disrup ls a program's c,,,'"llliM is.a
t'lCa:puon ·

S '011: na•pl liluck deal~ with lht• !'~replion, II ii !X\W


S.

b try, tlecpl, flnally I, Ilic Cttlll'fl ord1•r of lih)l·ks In


cxC'Cplion h.,ndling.

- 0 Scanned with OKEN Scanner


-
' V !(11~ ( •
rxcIr
11nN llf..Nl)llNG

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)

Sol~,~ Probl, 111


I. What is an E:,:uplio11 1
Solution. Exrep tion in general refers to some contradictory or unusua
l situation which can be
encountered while executing II program.
l Wl1e11 is Ercq11io11 Hmulliug req11irrd ?
Solution. The excep tion handling i.~ ideal for :
• prOt'esslng exceptional situations
• proct'Ssing exceptions for components th.it rnnnot handle them
din.'ctly
• processing exceptions for widely used compoll('IIIS !Mt s},ould not prore!:S
Uicir O\m c...:reption.s
• large projects that require unifom, error-prores.'111&·

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

._,\ '~" ,\,t, u,11!<•• ,,1f\11 J•lhn1 l,.-11rlllnr, Mr ,.


1
(1) ''" ' 'l'4~"' h,,n,llh~1 ""I'"~""''"'" h, 11,1111111 lfl< f,. / mn
1 '""'"JI ""
..,
fn) It ,·l,11il1t" llw- '""' nn,t, nhnn,111 ,,..,l~loilll) ~, ufK! 1,,~,rirnu 1n ,,n,, lfl1ltllot>t
1
(1/1)h ~1in111l•h" ""'~t1n1n-. n• ll1t•~'lmr•h•11tlll11r, l~~r '- P w• '
(irl rt nu\.~ '"' dN1, ruhu<I. !Aull -lulcrnnl I'"'&'~"'"·
1
~ \\'for,, ~ J\'11 t1,\I/ •n11l1~,/r rtrrpl /1411,//r,< - rl<f/•limi r,tr/1inK Noel•
•f I throw t'Y.crpljon,;. In wd, cr.e, ,_
""'''""' &in1cl Imr~ progr~m hn$ moi~ lhnn one roniI11 on o ·
mn l\.~-O.'iAt\' nu•rc lh~n one u-ccpl blod<s wilh n lry block
~ 11?-.-I ~ 11:t. " "''" '' /'Tl\1uml by fol/mriug rode. if the inpul gi1K11 ls: <•I 6 (bl O (c) r,.7 (4) • ~

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)

(c} uiport niyaodule

(d) X" 8 (r) mylist ~ (2, 3, 4]


print(X) pri nt(11yli.st[ 4])
1/t l.q,ortmath ~) filena.ae = "gr-eat. txt•
a •llilth. pow(leeeee, 1eeeee) open( "graet. n.·t", •r·)

Q Scanned with OKEN Scanner


ll
"I~ I I,n rum~ 11,\NllllNCl
~1'rN, · /1.7.5
~,1..111,11 (II) \'nlw•lli " '' (f•) i'r111Dl1•lqJon llru,,
(r) l111pn111 rrur
(,'I tmlt•,H11,11 (n ( h •1•1 ll11wH, HII
(R) lnJ!rr11r

,,.
, ' 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'

NCERT Chopler 1 : Exceplion Handling in Pyfhon


1. "Every syutn:r error is nu e:rccplio11 /ml i:very cxccplio11 m,11101 lien sy111n.1· am.• /11,lif.v lh<' ,1atm1ml.
Ans. An cxccplion mcans occurrcnre or some uncxpcctrd cvenl. SyntJx c!l'llr occur$ when sonw
language rules are violated, which is unexpccled event nncl hcnre Ciln bt> temuid "" e-..c,·ption.
However, exception means occurrence or uncxpcclt'<I l'l'L'nl causin~ pn,i;rJm di,mption durini;
runlimc, while syntax errors arc caught during compile tinw onlr,
Hence "every synlax t•rrur ban t•xc,•plion but ,•1·,•ry ,.,..,•pt11•n <',11111,11 l'<· ,1 >\'Illa, ,•rwr."
2. Wlw1 nrt /ht following b11ilt-i11 1•xc1•11tio11s rnisi•tl ? Gilh' ,·.w11111/,•, l1• ,11111~•rl y,•ur nusu,·n:.
(n) lmportError (/1) IOError (r) Nilm~Error (ii) Z,•mOil'isicmlirrw
Ans. l'or exception details, rdcr In tilblc I. l'lir cx11mpl1•, of lhL•,c ,•~,,•pti,11t~:
(n) llcfcr to Q. 8(c) (fi) Refer to Q. 8t~} (c) IM,•r l\1 Q. $(,f) (1/) IM,•r 1,, Q. li(/1)

0 Scanned with OKEN Scanner


I A.26
1
o1,•r tllfl '.,Clfll<_l Vnllt

1 11111
r,r, 1,,11

,,,,mf,-r~ pnd rll•pl•y 111, 1""1,


' It

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

6. &p!ntl a/thing t=plions using lrJ and aapl b/od:.


Ans. (o) Refer Section E.4
7. Consid6 IM /XJ/U grot,i bdoru 1111d fill in lk bllnJs.
print (·Learning Exceptions •.. •J
try:
flLllll int(input c•enter the first nui:ber")
C

nta2 =int(input("Ent er the second ni.t,er· ))


quotient = ( nlllll1/n11112)
print(•Both the nuabers entered were correct")
exc ept ___ _ I to enter only integers
print (·Please enter only ntllllkrs")
exc ept ____ # Oenocainator should not be zero
printc·11umber 2 should not be zero")
else:
print("Great •. you are a good progralllller")
_ _ _ _: I to be executed at the end
print ("l080VER... GOGETSCM R£ST")
Ans.
print ("learning EJ<ceptions ••. •)
try:
IUll • lnt(input("fntcr the first numbi!r"))
011112 • int(input("Enterthe se<ond nlleber•))

0 Scanned with OKEN Scanner


I

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.

r:se avs c 4-i


7
=
1. 1%~1 is csctpllon 7 Whnl Is cxctplion h.indling 7
2- Why i~ ext'.-pllon h.lndling i =l)' ?
3. Holl' Jo l'm r.liSC nn cx~plion7 Cfve code example,
4, How do )'OU handle nn cx~lion in J>ylhon 7 •
7
s. O-.~b e 1hc keyword try. Whnt is lhc role of try block
6. l'rc-dict 11~ output by following code :
iqiort math
deff(x):
ifx<= 8;
raise ValueError('f: argument
aust be greater than zero')
return math.sqrt(x)•2
def g(x):
y • f(x)
print (y > 2)

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:

f = open(filename, 'r') f • open(filena11e, 'r')


else: except IOError:
print ("file does not exist") print ("file does not exist" )
7
8. Which of the following four oulpuls is producrd ~)' the code Omt follows
outpul 1: oulpul 2 :
-2 -1 -2 -1
· 1 -1 -1 - 1
0 integer di vision or modulo by zero 0 integer division or modulo by zero
11
20

Qi Scanned with OKEN Scanner


p 1 111111111 11/11 II 1111 If ,
,.rr1iJ/ll\ I

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,

Q 1 Scanned with OKEN Sca nner )

You might also like