0% found this document useful (0 votes)
78 views17 pages

Adobe Scan 10 Sep 2024

Uploaded by

aravsameep
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)
78 views17 pages

Adobe Scan 10 Sep 2024

Uploaded by

aravsameep
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/ 17

---------·---------------

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 ·

Broadly there are two types of errors : . . .


. . .. . Tl e are the errors resultmg out of v10lation of prograrn .
( i) Comptle-t,me e1101s... ,es , ,,' writing syntactically
. . . .
mc01rect statement like :
rnino
o
1
language's grammai Ill es e.c::,.,
print ( "A"+ 2)
will result into compile-type error because of invalid syntax. All syntax errors are
reported during compilation.
(ii) Run-time errol's. The errors that occur during runtime becau~e of unexpected situations.
Such errors are handled through exception handling routines of Python. Exception
handling is a transparent and nice way to handle program errors.
Many reasons support the use of exception handling. In other words, advantages of exception
handling are :
(z) Exception handling separates error-handling code from normal code.
(ii) It clarifies the code (by removing error-handling code from main line of program) and
enhances readability.
(iii) It slin:ulates consequences as the error-handling takes place at one place and in one
manner.
(iv) It makes for clear, robust, fault-tolerant programs.
So we can summarize Exception as :
I 15
. .
t an exceptional event that occurs during runtime and causes normal program flow to be disrupted.
Some common examples of Exceptions are :
¢) Divide by zero errors

¢) Accessing the elements of an array beyond its range


¢) Invalid input
¢) Hard disk crash
¢) Opening a non-existent file I EXC EPTION HAN DLING
¢) Heap memory exhausted Way of handling anomalo~
situations in a program-run, 1$
For instance, consider the following code :
known as Exception HandHng.
>» print (3/0)
If you execute above code you'll rec .
, e1ve an error message as .
Traceback (most recent call last ) : ·
File "<pyshell#0 >" , line 1, in <module>
print 3/ 0 t
ZeroDi visionError: integer di vi .
s1on or modulo by zero
' " @· ~

EPTION HAND LING 261 ~


r 6 : EXC
o,apte
Pytho n. The defau lt excep tion
is n,essage is genera_ted by defau lt excep tion handl er of
fh . does the follow mg upon. occur rence of an Exception ..
handler . .
· ,ts out excep tion descn phon
(i) Prll . .
st
Prints the ack trace, ,.e., luera rchy of meth ods where the excep tion occur red
(ii)
Causes the progr am to termi nate.
(iii)

concept of Exce ption Hand ling


6.3 ::.-- - is, write your code m such a way
fhe global conce pt of error- handl it~g is pretty simpl e. That
g. Then trap thjs error flag and ii
that it raises some error flag ever~ tune s~me thing goes wron
am flow shoul d be some what
this is spotted, call the error hand lmg routm e. The inten ded progr
like the one show n it1 Fig. 6.1.
fhe raising of imagit1~ry
is called throw ing 3
error fl ag Write code
or raising an error. When an such that it
Call
. 2 the
error is throw n, the overa ll raises an
g every If error flag Error-
error-fla handling
system respo nds by catchit1g time something t---- +---. - _- d_t_ h--+-----...i
Is raise en routine
goes wrong
the error. And surro undm g a
block of error- sensit ive- throw exception catch exception

code-with-exc eption -hand lmg


is called trying to execu te a I"' F'1gure 6.1 Concept of except ion handlin g.
block.
Some termmology used withi n excep tion hand ling follows.
-- . - ~ -~
~.·-.,- ; -

Description Pythp n T.erminolof!V


- ···-
e Excep tion
I An unexpe cted error tha t occur s during runtim.
I try block
A set of code that might have an excep tion throw n in it.
Throw ing or raisin g an error
The process by which an excep tion is gener ated and p assed
to the prol!Tarn. '

occur red and execu ting Catch ing


Capturing an excep tion that has just
statements that try to resolv e the p roblem
except clause or except/exception
The block of code that attem pts to d eal with the excep tion
/i.e., problem). block or catch block
the Stack trace
The sequence of metho d calls that broug ht contro l to '
point where the excep tion occur red.

When to Use Exception Hand ling • J;::TE:::


'AfO
The exception hand ling is ideal for :
An except ion can be genera ted
¢) processmg excep tiona l situat ions. by an error in your progra m, or
¢) processmg excep tions for comp onen ts that
canno t explici tly via a raise statem ent.

handle them direc tly.


~ large projects that requi re unifo rm error- proce ssing .
IJor-r-- l WYif
lJnhandl
ed excepti .
ons will cause Python to halt execut ion.
262 COM PUTE R SCIENCE WIT
H PYTHON
6.4 Exception Handling in Pyth on ' X11

Exception Han dlin g in Pyth on invo lves the use


of try and exce pt clau ses in the foll .
whe rein the code that may generate_ an ~xce~tton . . ·t .
_ 1s w~1 ten_ m th e try block andow1n gf
the orl'l1at
hand ling exce ption whe n the exce ption 1s raise
d, 1s wnt ten m exce pt block. cocte for
See belo w:

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

For insta nce, cons ider the follo wing code :

try :

prin t ("re sult of 10/5 = ", (10/ 5))


prin t ("re sult of 10/0 = ", (10/ 0)) ~ The code that may raise an
- exception is written in try block
This is exception exce pt :
block ; this u~·11
execw e when the , ~
exception is raised ~ J - prin t ("Di vide by Zero Erro r! Den omin ator mus t not
.• be zero !")

The outp ut prod uced by abov e code is as show


_o~ - ~ ■ dMGn~TIGU~ D~NaU
m•Q··

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

See, now the outp ut prod uced does not show


the scar y red- colo ured stan dard error message;it
is now show ing wha t you defi ned und er
the exce ptio n bloc k.
Con side r anot her code that hand les an exce ptio
n raise d whe n a code tries conversion from text
to a num ber:

try:
x = int(" XII" )
exce pt:
prin t ("Er ror conv ertin g 'XII' to a number")

The outp ut gene rated from abov e code is not


the usua l erro r now , it is:

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

ter an integ er:.doo7


.
En Not a val, integ er.
uro r •1
Enter an ; ntege r: 007

.4_ l Gene ral Buil( in Python Excep tions


6 excep tions of Pytho n. The built- in
In this sectio n, we are discu ssing abou t some built- in in
excep tions can be gener ated by the interp reter or built- in funct ions. Some comm on built-
excep tions in Pytho n are being listed below in Table· 6.1.
p ble 6.1 Some built-i n Exceptions
- -
., Description
I Exception Name
end-of-file condi tion (EOF)
IEOFError Raised when one of the 'built-in functi ons (input ( )) hits an
and file.re adline ( ) metho ds return an
witho ut readin g any data. ( NOTEthe file.read( )
empty string when they hit EOF.)
the built- in open( ) functi on
Raised when an 1/0 opera tion (such as a print statem ent;
I
110 Error reason , e.g., "file not found " or "disk
or a metho d of a file object) fails for an 1/0-re lated
I
full" .
s only to unqua lified names.
NameError Raised when a local or global name is not found . This applie
that could not be found .
The associated value is an error message that includ es the name
a list of length 4 if you try
lndexError Raised when a sequence subsc ript is out of range, e.g., from
y trunca ted to fall in the
to read a value of index like 8 or - 8 etc. (Slice indice s are silentl
is raised .)
allow ed range ; if an index is not a plain integer, Ty_e.eError
defini tion or when a from ...
lmportError Raised when an impor t statem ent fails to find the, mod_u le
impor t fails to find a name that is to be impor ted.
of inapp ropria te type, e.g.,
TypeError Raised when an opera tion or functi on is applie d to an object
if you try to comp ute a squar e-roo t of a string value.
The associ ated value is a string
,_
giving detail s about the type mism atch.
argum ent that has the right
VaiueError Raised when a built-in opera tion or functi on receiv es an
descri bed by a more precis e
type but an inapp ropria te value , and the situat ion is not
1- excep tion such as IndexError.
· ··
ZeraD v1szonError lo opera tion is zero.
,--::.::;:1 Raise d when the secon d argum ent of a divisi on or modu

,~
[~

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:

Now the abov e outp ut may be of one of the two reaso


ns:
(i) the file did not exist or (ii) there was no data in the file.
But the abov e code did not tell whic h cause d the error
.
6.4 .2 Seco nd Argument of the except Block
You can also prov ide a secon d argu ment for the excep
t block , whic h gives a reference to the
excep tion object. You can do it in follo wing form at :
try:
# code
exce pt <ExceptionName> as <exArgument> :
# .hand le erro r here

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

6.4.3 Hand ling Mult iple Errors


.
Mult iple types of error s may be captu red and proce ssed rovid~1
diffe rentl y It can be useful to P turt'
m ore exact error message to the user than a simple "an .
error has occurred." In ord er to cap
chl1111'
and proce ss diffe rent type of excep tions, there must
be mult iple excep tion blocks - e~
perta ining to diffe rent type of excep tion.
EPTION HANDLING
6 . EXC
chapter .
. . done as per following format :
ThIS IS

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.

Program to handle multiple exceptions.


try:
my_file = open("myfil e. txt")
my_line = my_file. read line()
my_int = int ( s . strip())
my_c alculated_v alue = 101 / my_int
These three except blocks will catch and
except IOError : handle IOError , ValueError and
print ("I/O error occurred") ZeroDivisionErr or exceptions respectively

except ValueError:
print ("Could not convert data to an integer.")

except ZeroDivisio nError:


print ("Division by zero error")
except: The unnamed except block will
print ("Unexpected e r r o r : " ) - - - - - - - - handle the rest of the exceptions
else: ·
print ("Hurray! No exceptions! ") ...,.,__ __
- This last else: block will get executed
The outp t d if no exception is raised
u pro uced b y above code is :
I/o error occurred

Exception H di· . ffl-: ,11:.,_ _ _.....;.._ _..:1......_·_*----17


an rng - execution order
The <try sw·t e> 1s
. executed first ·
'AJorE
, The named except: blocks handle
.
if, during the course of executing . an the named exceptions while the
the <try swte>,
excepti ·1 . unnamed except: block handles
on s raised that is not handled otherwise, and
the <exce t . . all other exceptions - exceptions
ex . P swte> 1s executed, with <name> bound to the not mentioned in named except:
ception .f f . . . .
unnanzed ' 1 ound ; if no matching except swte 1s found then blocks.

.....___ except suite is executed .


COMPUTER SCIENCE WITH PYTHON
- XII

6.4 .4 Thefinally Block


. 11y: blo ck along with a try· block, just like you use except: block
You can a lso use a f1na · ' e·g·, as:
try :
# statem ents that may raise excep tion
[excep t:
# handle excep tion here]
finall y :
# statem ents that will always run
The difference betwe en an except: block and the finally : block is that
the finally : block is a place
that contai ns any code that must execute, wheth er the try: block
raised an exception or n~t.
For examp le,
try:
fh = open("poems. txt", "r+")
This statemen t will always be
fh. wri te("Ad ding new line") executed in the end
finall y:
print ("Erro r: can\'t find file or read data") ~
~ p·
You may combi ne finally: with except: clause . In such a combi nation
, the except: block will get
execut ed only in case an except ion is raised and finally : block will
get execut ed ALWAYS, in
the end. Follow ing code illustr ates it :
try:
fh = open("poeml. txt", "r")
print ( fh. read ())
excep t:
print ("Exce ption Occur red")
finall y:
print ("Fina lly saying goodb ye.")
The outpu t produ ced by above code will be :

This is printed because Exc~ption Occur red ._.6_


- __ This is printed because except: block
finally: block got executed - - - . got executed when exception occurred.
in the end. Fina11 Y sayi ng goodbye
In the above code if no excep tion is raised , still the above code
w ill print :
Finall y saying goodbye
becau se finally : block gets execu ted alway s in the end.

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 ) ... ..
·.
••
..~

The t)utp ut prod uced by abov e code is :


Enter nume rator : 7 • • ••• • • • ~
Enter deno mina tor : 0 • · •
•~ . This was the custo,,:,-message sent; printed
~ as str(e) because the exception
Exception 7 /0 not poss ible .. ' ~ reference was receive
d in e

ement s and test-conditions required. So in progr ams


In some situations, you have a clear idea about the requir
where results being different from the expec ted results
where you know the likely result s of some conditions and
ent if the condi tion is resulting as expec ted or not.
can crash the progra ms, you can use Pytho n asser t statem
a condition. If the condi tion is true, it does nothi ng and
Python 's assert statem ent is a debug ging aid that tests
assert condi tion evalua tes to false, it raises an
your program just contin ues to execu te. But if the
ge. The syntax- of asser t statem ent in Pytho n, is :
AssertionError excep tion with an option al error messa
asse rt cond ition [, erro r- mess age ] s1- - - Specify the optional, custom message
thro11gl, error_message
For example, consid er the follow ing code :
print ("En ter the Num erato r: ")
n = int ( i npu t ()) ~
Cust?m Error message
- - - specifie d
iiA/ :' .----_,;_~---I
0 TE

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 .

TRU E/ FALSE QUE STIO NS


l. Exce ption and error are the same .
2. All type s of erro rs can be foun d duri ng
comp ile time .
3. A prog ram runn ing prop erly put prod ucin
g wron g outp ut is an exce ption .
4. Unex pect e d rare con d 1·t·1011 occu rrmg . .
· d urm
· g runt ime
whic h disru pts a prog ram' s execu t·on
1 15 a11
exce ption .
5. The exce pt bloc k deal s with the exce ption
, if it occu rs.
6. try, exce pt, final ly is the corre ct orde r of
bloc ks in exce ption hand ling.
7. An exce ption IT' .:l / 1--,,, ··- ·Jed even if the •tl11
prog ram is synta ctica lly corre ct. [C13SE 51' • •. :ll
EPTION HANDLING 26 9
6 . EXC
cnoPter .
ASSERTIONS AND REASONS

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

-+. \Mwt arc t'1e ndvn11tages of exception '1a11dling ?


Solution. Advantag es of exception handling are:
(i) Exception handling separates error-han dling code from normal code.
(ii) It clarifies the code and enhances readabilit y.
(iii) It stimulate s conseque nces as the error-han dling takes place at one place and in one
rnanner·
(iv) It makes for clear, robust, fault-tole rant programs .

5. \t\lhen do you need multiple except handlers - exception catching blocks ?


Solution. Sometimes program has more than one condition to throw exceptions. In such cases, one
. bl k
can associate more than one except blocks with a try oc .

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)

def divi de(x , y):


try:
resu lt = x/y
exce pt Zero Div isio nErr or:
prin t ("di visi on by zero !")
else :
prin t ("re sult is", resu lt)
f inal ly :
pr int ("ex ecut ing fina lly cla use" )

Solut ion.
resu lt is 2
(a) divide(2, 1)
exec utin g fina lly clau se

(b) divide(2, 0) divi sion by zero !


exec utin g fina lly clau se

(c) divide("2 ", "1")


exec utin g fina lly clau se
Trac ebac k (mo st rece nt call last ):
File "<py shel l#46 > ", line 1, in <module>
divi de(" 2", "1")
File "C : /tes t16 . py", line 22, in divi de
resu lt= x/y
for /: 'str' and 'str'
Typ eErr or: unsu ppor ted oper and type (s)

If CE.I< I ■♦.J
.·_.->~

'1
NCERT Ch t 1 ption rlan dl,:t-,g in Pxth I
on ' '

op er : Exce ' I 11 11t'!·,,, I I • I '


I. ''£ tltt statt.>m<?nt.
very syntax error is.an exception 'but' evem
; fXception qmn at /Je 11 synta x error." fu ~tify
I. n som e
e une}.(pected :eveµt. Synt ax erro r occu rs whe
,
Ans. An . . 1 : 1

lan · exce ption mea ns occu rren ce of ,som 1 ption .


guage rul~s are viol ated, whic h is'I uhex pect ed evep t a:nd henc e c&n be term ed as exce
I I :1· . i .
B I
, ce. @f une;xpected, .,eve,n~ caus ing . prog ram l 1srnp t10n c unn g
owev ·
er' ex cep t·ion m~a ns occu rren
rllntii . ' . I 'I ' '
ne h. ax erro rs are caug ht c
. lirip g eoijl nile \frne ,only•
1.J ' w Ile ,synt ' . -, I
'
n.ence "
ever y synt ax erro r 'is an exce ption , but ~:v efY ex~e ptio n cannot be a syntax error."
,,
2· 1•vhen · · , , 1 fl .
-in excep tiorts raise d ?, Give Gxnmples to 1w ppor t your misw;.:1 s.
(a;: :he f ollowing built
/(c~ Nc1n1eEri-or (d) Zero Div ision Erro r
A. por.t Erro r (b) IGE rror . .
,. '
ns. 1Fore e 6.1/F or exam ples of these exce ption s :
(a) , xcep t\on deta ils, refer to Tabl
· Refe r110 'Q·.,8(c)' · ' (b) ,~efe r to Q. 18(g)
'(c) .R,
~fer to Q · B(d)· (d) Refe r to Q. 8(11)
27 2 COMPUTER SCIENCE WITH PYTHo
N ' Xii
3. W/1nt is tl1e use oif 11 raise stntement 7 Write a code, to accept tw<1i 1 numbers and display th
"
Appropriate exceptio11 should be mised .if thf user
' ' d
enters the secon num ber (denommator)
,i " e quotien
as zero (O). t.
Ans. The raise keyword is used tb manually raise an ex12eption like exceptions are raised by p
l·t seIf. I I
1
Yhon
I
I
a = int ( input ("Enter value fo r, a, : "))
b = int ( input ("Enter value for b :1" ) 1)
I II
try:
if b==0: I '

raise ZeroDivi!sion Error # 11ad.!sing exception using raise keyword


print(a/b)
except ZeroDi visionErr'o r:
print( "Please enter non-zer,o val~e for b. ")
4. Use assert stateme11t in Que~tfon No. 3 to test the division expression in the program.
Ans.
a = int ( input ( "Entel'i' va,l u~ for a ,: "))
b = int (input(:" Enter yalue ,f qr .b ,: ")).
assert b ! = 0, "Value for lb must be .non-zero"
print(a/b) 1,
I
7. Consider the code given below and fill in the blanks.

print (" Learning ExFept:i!b~i ... ")


try: ,
I I 11 : ii ' '
numl = int'(inpu:t 11
( "Enter the' first number")
'
num2 = int1(i,-iput( "Einter the second number")) ,
.
quotient= h I ,11 I . , ,, I ,, ' 'I
~ uml:/inum:2')' ' 11 1: ,,1 : • • ' . I. '!
I
! I q 11 ' • ' I
0
print( "Bothi;hlj! riumb~r,s :e ntered 1,,:.1ere' correct") ·.
'l1i/i: 1: 11f::. !: 1:l!,li' JI' ,! 111\'tl# i~~i-~~t i~ r:dnil.'y linteger:-s
l
1
except .
print ( "Plea's e ente'r only riumbens'1'/') ,: ' 1 ' ,·
11 I
except
' '
,. 1 , ·
· ·•1 ' •I· i' 1 1 'I
I ,.
' ' I
•11 I ' 1 1 11, i' ,:
'ii
L
'111 # Denomilnatori sh0ulld 'n0t be zero
. t( "N b ., I I I '
pr1n um er 2 sh0uld nbt1be zero" 1 I 1·11 I I' 'IJI'
I 'I ~ 1'
;, ' I I' I ' 1
else: I
1
<I I I ,,
' ,' ' II''/' I
• " I ' '1 I Ii I ,' 'I\
print( Great .. you are a go9d programmer") , !'.,
_____: i . # to be executed at 'the/end
print ("JOB OVER. : . GO GE[f lSOME REST I' ).
1
Ans.
print ("Learning Exceptions ... ")
try:
numl = i'nt(input(''E'nt~r the f i rst number l')I) I
I I
num2 = int ( input( "Ent~r the sec91')d nµmber" )')
quotient= (numl/nl'.lm2) 1 ,
1
print ("Both the numbers entered w~re correct,, ),
11
except ValueError: · ,
# ;to enter1only i!nteger~
print ( "Please enter pnly ,number:-s ''')
. EXCEPTION HANDLING 273
c1i0Pter
6 .

except zeroDivis ionError: # Denominat or should not be zero


print( "Number 2 shouild not be zero")
else:
print( "Great .. you are a good programme r")
~ : # to be executed at the end
print ("JOB OVER, .. GO GET SOME REST")
Yoll T,ave learnt how to use math module i11 Class Xl. Writ e II corle iul,crc yo11 11se the wrong m11n/Jer of
8
· arguments for a method (say sqrt() or pow()). Use tl,c excc11tio11 l1a11rlli11s process to catch tile ValuPError
exception.
Ans.
import math
print ( "Code to test wrong TYPE of a r;-guments" )
try:
numl = int(input ("Enter the, fi 11st nurriber"))
resultl =math. sqrt(numl )
print ("Sqrt:", resul tl)
except ValueErro r: # to enter only integers
print ( "Please enter only Positive numbers")
try:
num2 = int ( input ("Enter the ,s econd numoer"))
result2 = math.pow( numl, num2)
print ("-Pow: ", rest!i l t2)
except ValueErro r: # to enter only integers
print ( "Please enter only numbers")
finally: # to be executed at the end
print( "Tested only wrong types; Wrong no. of requires requilres *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; wrong no. of requires requires '~ args
Code to test wrong TYPE of arg·u ments
Enter the first number6
Sqrt: 2 .449489742 783178
Enter the second number4
Pow: 1296.0
st
Te ed only wrong types; wrong no. of requires requires *args

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

Exception An anomal ous situation encountered by the program .


Syntax error Prograrnrning languag e' s gramm ar ru les violatio n error.
Compile time errorError that the compile r/ interpreter can
find during compi lation .
Run time error Error during program execulion.

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

You might also like