0% found this document useful (0 votes)
19 views21 pages

Errors and Exceptions - Sheetal Taneja

Uploaded by

sanujiyas101016
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)
19 views21 pages

Errors and Exceptions - Sheetal Taneja

Uploaded by

sanujiyas101016
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/ 21

dump(): to con v er t a str u ctu r e to by te str ea m a n d w r ite it to

a file

load(): to r ea d a by te str ea m fr om a file a n d con v er t it ba ck


to th e or ig in a l str u ctu r e

On executing script in Fig. 9.1, Python responds with


the following output:

['hello', 'world'] {1: 'one', 2: 'two'}

9.3 ERRORS AND EXCEPTIONS

Errors occur when something goes wrong. We have


encountered several errors in our program such as index
out of bound, division by zero, and invalid cast
operation. The errors in Python programming may be
categorized as syntax errors and exceptions. A syntax
error occurs when a rule of Python grammar is violated,
for example, a syntax error occurs in the following call
to print function because of missing quote mark at the
end of the string. Similarly, missing colon in the for
statement results in a syntax error.

sy n ta x er r or : v iola tion of Py th on g r a m m a r r u le

>>> print('Hello)

SyntaxError: EOL while scanning string


literal

>>> for i in range(0, 10)

SyntaxError: invalid syntax

Another common error in Python programming is


caused by incorrect indentation. Often it leads to a
syntax error, but incorrect indentation may sometimes
lead to a logical error that alters the intended meaning of
the program that is difficult to locate.

In den ta tion er r or

In contrast to a syntax error, an exception occurs


because of some mistake in the program that the system
cannot detect before executing the code as there is
nothing wrong in terms of the syntax, but leads to a
situation during the program execution that the system
cannot handle. For example, opening a non-existent file
for reading, attempting to access value of a variable
without assigning a value to it, and dividing a number
by zero. These errors disrupt the flow of the program at a
run-time by terminating the execution at the point of
occurrence of the error. We have noticed that whenever
an exception occurs, a Traceback object is displayed
which includes error name, its description, and the point
of occurrence of the error such as line number. Now we
describe some commonly encountered exceptions:

exceptions: er r or s th a t occu r a t ex ecu tion tim e

1 . NameError
Th is ex ception occu r s w h en ev er a n a m e th a t a ppea r s
in a sta tem en t is n ot fou n d g loba lly . For ex a m ple, in
th e follow in g sta tem en t, w e in ten d to ta ke m a r ks a s a n
in pu t fr om th e u ser . For doin g so, w e in ten ded to u se
fu n ction input bu t in stea d ty ped Input. Py th on bein g
ca se-sen sitiv e fa ils to r ecog n ize th e fu n ction input a n d
th e sy stem r espon ds w ith th e er r or m essa g e
NameError: name 'Input' is not defined. Th is
m essa g e beg in s w ith th e n a m e of th e ex ception . Note
th a t th e follow in g Traceback object descr ibes th a t
er r or occu r r ed in lin e 1 in Py th on sh ell, in th e m ost
r ecen t ca ll:

name not f ou nd gl ob al l y

>>> marks = Input('Enter your marks')


Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
marks = Input('Enter your marks')
NameError: name 'Input' is not defined
Note th a t th e a bov e er r or cou ld n ot h a v e been detected
a s a sy n ta x er r or a s it is per fectly fin e to defin e a
fu n ction Input a s sh ow n below :

>>> def Input():


return input('Enter your marks: ')
>>> marks = Input()
Enter your marks: 78
>>> marks
'78'

Sim ila r ly , a ccessin g th e v a lu e of a v a r ia ble befor e


defin in g it r a ises a n ex ception :

>>> print(price)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print(price)
NameError: name 'price' is not defined

2 . TypeError
Th is ex ception occu r s w h en a n oper a tion or fu n ction is
a pplied to a n object of in a ppr opr ia te ty pe. For ex a m ple,
th e ex pr ession 'sum of 2 and 3 is ' + 5 in v olv es
a ddin g a n u m ber to a str in g w h ich is n ot a v a lid
oper a tion r esu ltin g in a n ex ception .

Inv al i d t y p e of op er ands f or t h e op er at i on

>>> 'sum of 2 and 3 is ' + 5


Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
'sum of 2 and 3 is ' + 5
TypeError: must be str, not int

3 . ValueError
Th is ex ception occu r s w h en ev er a n in a ppr opr ia te
a r g u m en t v a lu e, ev en th ou g h of cor r ect ty pe, is u sed
in a fu n ction ca ll, for ex a m ple:

Inv al i d ar gu ment v al u e

>>> int('Hello')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
int('Hello')
ValueError: invalid literal for int() with
base 10: 'Hello'

Note th a t in th e a bov e ex a m ple, th e fu n ction int h a s


been in v oked w ith a v a lid ty pe of a r g u m en t, i.e. str,
bu t its v a lu e, i.e., 'Hello', ca n n ot be con v er ted to a n
in teg er . Hen ce th e ValueError.
4 . ZeroDivisionError
Th is ex ception occu r s w h en w e tr y to per for m n u m er ic
div ision in w h ich th e den om in a tor h a ppen s to be zer o,
for ex a m ple:

at t emp t t o di v i de b y zer o

>>> 78/(2+3-5)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
78/(2+3-5)
ZeroDivisionError: division by zero

5 . OSError
Th is ex ception occu r s w h en ev er th er e is a sy stem
r ela ted er r or su ch a s disk fu ll or a n er r or r ela ted to
in pu t/ou tpu t, for ex a m ple, open in g a n on -ex isten t file
for r ea din g or r ea din g a file open ed in w r ite m ode:

sy st em r el at ed er r or

>>> f = open('passwordFile.txt')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
f = open('passwordFile.txt')
FileNotFoundError: [Errno 2] No such file or
directory: 'passwordFile.txt'

6 . IndexError
Th is ex ception occu r s w h en ev er w e tr y to a ccess a n
in dex th a t is ou t of a v a lid r a n g e. For ex a m ple, let u s
n a m e th e list of color s ['red', 'green', 'blue'], a s
colors. Now th e v a lid r a n g e of in dex es for colors is
[-3, -2, -1, 0, 1, 2] a n d th e v a lid in dex r a n g e of
in dex es for th e str in g colors[2] is [-4, -3, -2, -1,
0, 1, 2, 3]. A ccessin g a n in dex ou tside a v a lid r a n g e
w ill ca u se IndexError exception to occu r :

ac c essi ng an i nv al i d i ndex

>>> colors = ['red', 'green', 'blue']


>>> colors[4]
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
colors[4]
IndexError: list index out of range
>>> colors[2][4]
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
colors[2][4]
IndexError: string index out of range

9.4 HANDLING EXCEPTIONS USING TRY…EXCEPT

We have seen several examples of exceptions that would


result in abrupt termination of program execution. Such
exceptions are known as unhandled exceptions. To
prevent a program from terminating abruptly when an
exception is raised, we need to handle it by catching it
and taking appropriate action using the try…except
clause.

Whereas a try block comprises statements that have


the potential to raise an exception, except block
describes the action to be taken when an exception is
raised. In the except clause, we may specify a list of
exceptions and the common action to be taken on
occurrence of any of these exceptions. Alternatively, a
specific action may be provided for each of the
exceptions separately. We can also specify a finally
block in the try…except clause, which is executed
irrespective of whether an exception is raised.

try block: sta tem en ts h a v in g poten tia l to r a ise a n ex ception

except block: a ction to be per for m ed w h en ex ception is r a ised

In the script try_except1 (Fig. 9.2), line 10 (within


except block) will be executed only when any input–
output related error is raised in line 8 that lies within the
try block. While executing this script, an attempt to
open a non-existent file will cause the IOError
exception and will yield the following output:

finally block: ex ecu ted ir r espectiv e of w h eth er a n ex ception


is r a ised
Fig. 9.2 Pr og r a m to open n on -ex isten t file (try_except1.py)

Problem with Input Output...

Program continues smoothly beyond


try...except block

Note that as IOError exception raised in line 8 had


been handled (lines 9–10), the program did not
terminate abruptly and continued smoothly to execute
line 11 after the exception was handled.

We can access the description of the Traceback


notice directly. For this purpose, the name of the
exception such as IOError is followed by the keyword
as, which is followed by a user-defined name such as
err in the except clause (Fig. 9.3). So, when IOError
exception is raised during execution of the open function
(line 9), the exception information is assigned to the
variable err and the message [Errno 2] No such
file or directory: 'Temporary_File' is
displayed (line 11). It is also possible to track the
exception raised by Python using the expression
sys.exc_info(), which yield the details of the
exception as a tuple comprising the type of exception,
and description of the exception, a reference to the
exception object, for example, on executing the script
try_except2 (Fig. 9.3), the system responds as
follows:

tr a ckin g r a ised ex ception


Fig. 9.3 Pr og r a m to open n on -ex isten t file (try_except2.py)

Problem with Input Output...

[Errno 2] No such file or directory:


'Temporary_File'

(<class 'FileNotFoundError'>,
FileNotFoundError(2, 'No such file or
directory'), <traceback object at
0x02EB2530>)

Program continues smoothly beyond


try...except block
There may be situations when a sequence of statements
that appear in a try block can potentially throw more
than one exceptions. We can deal with such situations in
different ways: the first option is to enumerate all
possible exceptions in the except clause in the form of a
list, the second option is to define an except clause for
handling each exception separately, and yet another
option is to go for a defensive approach by placing the
targeted group of statements in try block and specify an
empty except clause. Such an except clause is capable
of catching all possible errors.

a n em pty except cla u se ca tch es a ll possible ex ception s

In the script pricePerUnit1 (Fig. 9.4), we wish to


compute the price per unit weight of an item. For this
purpose, we define a function main that takes price
and weight as inputs and computes the price per unit.
Note that ValueError and TypeError exceptions may
be raised while converting an argument to a float
value (lines 12 and 14) and ZeroDivisionError
exception may be raised while dividing price by
weight (line 16). For handling these exceptions, we
include all of them in the except clause (line 17). An
optional else clause (line 20) may also be specified in
the try…except clause, which will be executed only if
no exception is raised.
Fig. 9.4 Pr og r a m to com pu te pr ice per u n it w eig h t of a n item
(pricePerUnit1.py)

On executing the script pricePerUnit1 (Fig. 9.4),


the system prompts the user to enter values of price
and weight:

> >>

Enter price of item purchased: 400

Enter weight of item purchased: 0


Invalid input provided by user

(<class 'ZeroDivisionError'>,
ZeroDivisionError('float division by
zero',), <traceback object at 0x039BD2B0>)

As we have specified a common action to be taken on


each of the exceptions ValueError, TypeError, and
ZeroDivisionError, we could have replaced the
except clause:

com m on a ction s for th e ex ception s

except (ValueError, TypeError,


ZeroDivisionError):

by the empty except clause:

except:

However, it is often preferable to handle different


exceptions separately as shown in the script
pricePerUnit2 (Fig. 9.5). Also, we make use of the
assert statement in line 13 to ensure that price and
weight are positive values. An empty except clause is
used (line 21) to catch all other exceptions (for example,
invalid range).

It is pr efer a ble to h a n dle differ en t ex ception s sepa r a tely


Fig. 9.5 Pr og r a m to com pu te pr ice per u n it w eig h t of a n item
(pricePerUnit2.py)

Next, we present the system response on execution of


the script pricePerUnit2.py on different inputs:

Enter price of item purchased: 20


Enter weight of item purchased: x

Invalid inputs: ValueError

Enter price of item purchased: -20

Enter weight of item purchased: 10

(<class 'AssertionError'>,
AssertionError(), <traceback object at
0x0356D328>)

Enter price of item purchased: 20

Enter weight of item purchased: 0

Invalid inputs: (ZeroDivisionError)

Enter price of item purchased: 20

Enter weight of item purchased:

Invalid inputs: TypeError

Enter price of item purchased: -20

Enter weight of item purchased: 0

(<class 'AssertionError'>,
AssertionError(), <traceback object at
0x03B42508>)

When we enter the inputs -20 and 0, each of the


assert statement (line 15) and division operation (line
16) can raise exceptions. However, as the assert
statement is encountered before the division operation,
in the try…except clause, AssertionError exception
is raised. As none of the exceptions specified in lines 17,
19, and 21 matches the AssertionError exception, the
empty except block (lines 23–24) got executed. Thus,
line 16 got skipped.

A segment of the script that handles an exception is


called a handler. In the above script, the exceptions were
raised and handled within a try…except block.
However, if an exception is raised in a try block, but the
script does not include the corresponding handler in that
block, then search for a handler is continued in the outer
try…except block, and so on. We illustrate this in the
script pricePerUnit3 (Fig. 9.6) – a slightly modified
version of the script pricePerUnit2 (Fig. 9.5). In this
version, each of the lines 13 and 18 is placed under a
separate try…except block, which catches only
ValueError exception. So, when TypeError is raised
in line 13 or line 18, Python does not find any matching
except clause in the inner try…except block and the
search for the corresponding handler continues in the
outer try…except block, where we find the required
handler and the function main prints the string
Invalid inputs: TypeError'.

If th er e is n o h a n dler for th e ex ception r a ised in tr y block,


sea r ch for h a n dler ta kes pla ce in ou ter tr y ...ex cept block
Fig. 9.6 Pr og r a m to com pu te pr ice per u n it w eig h t of a n item
(pricePerUnit3.py)

If we wish to execute some action(s) irrespective of


whether an exception is raised, such action(s) may be
specified in the finally clause. Further, an exception
may be raised explicitly using the keyword raise,
followed by the name of the exception, followed by the
string (enclosed in parentheses) to be displayed when the
exception is raised. For example, in the script
raiseFinally1 (Fig. 9.7, line10), if the value of the
variable marks is out of the valid range, i.e. marks < 0
or marks > 100, the exception
ValueError('Marks out of range') is thrown.
As the exception is not handled using an except clause,
the program terminates by throwing the unhandled
exception on invoking the print function in the
finally clause.

u se raise key w or d for ex plicitly r a isin g a n ex ception

a n u n h a n dled ex ception lea ds to pr og r a m ter m in a tion

>>>
Bye

Traceback (most recent call last):

File "F:/PythonCode/Ch09/except.py", line


16

main()

File "F:/PythonCode/Ch09/except.py", line


10, in main

raise ValueError('Marks out of range')

ValueError: Marks out of range


Fig. 9.7 To illu str a te th e u se of r a ise a n d fin a lly cla u ses
(raiseFinally1.py)

Next, we modify the script raiseFinally1 by


including an except clause (Fig. 9.8) so that the
program continues smoothly after the exception is
raised.

> >>

Bye

Program continues after handling exception


Fig. 9.8 To illu str a te th e u se of r a ise a n d fin a lly cla u ses
(raiseFinally2.py)

9.5 FILE PROCESSING EXAMPLE

In this section, we will develop a program to moderate


the results in an examination. We are given a file named
r a ised. In th e except cla u se, w e m a y specify a list of
ex ception s a n d th e a ction to be ta ken on occu r r en ce of
ea ch ex ception .
2 5 . finally block is a ssocia ted w ith try…except cla u se
a n d is ex ecu ted ir r espectiv e of w h eth er a n ex ception is
r a ised.
2 6 . Deta ils of th e ex ception r a ised by Py th on ca n be
a ccessed fr om th e object: sys.exc_info().

EXERCISES

1 . Wr ite a fu n ction th a t ta kes tw o file n a m es, file1 a n d


file2 a s in pu t. Th e fu n ction sh ou ld r ea d th e con ten ts
of th e file file1 lin e by lin e a n d sh ou ld w r ite th em to
a n oth er file file2 a fter a ddin g a n ew lin e a t th e en d of
ea ch lin e.
2 . Wr ite a fu n ction th a t r ea ds a file file1 a n d displa y s
th e n u m ber of w or ds a n d th e n u m ber of v ow els in th e
file.
3 . Wr ite a fu n ction th a t ta kes da ta to be stor ed in th e file
file1 a s in ter a ctiv e in pu t fr om th e u ser u n til h e
r espon ds w ith n oth in g a s in pu t. Ea ch lin e (or
pa r a g r a ph ) ta ken a s in pu t fr om th e u ser sh ou ld be
ca pita lized, a n d stor ed in th e file file1.
4 . Wr ite a fu n ction th a t r ea ds th e file file1 a n d copies
on ly a lter n a tiv e lin es to a n oth er file file2.
A lter n a tiv e lin es copied sh ou ld be th e odd n u m ber ed
lin es. Ha n dle a ll ex ception s th a t ca n be r a ised.
5 . Wr ite a fu n ction th a t ta kes tw o files of equ a l size a s
in pu t fr om th e u ser . Th e fir st file con ta in s w eig h ts of
item s a n d th e secon d file con ta in s cor r espon din g pr ices.
Cr ea te a n oth er file th a t sh ou ld con ta in pr ice per u n it
w eig h t for ea ch item .
6 . Wr ite a fu n ction th a t r ea ds th e con ten ts of th e file
Poem.txt a n d cou n ts th e n u m ber of a lph a bets, bla n k
spa ces, low er ca se letter s a n d u pper ca se letter s, th e
n u m ber of w or ds sta r tin g w ith a v ow el, a n d th e
n u m ber of occu r r en ces of w or d 'beautiful' in th e file.
7 . Wh a t w ill be th e ou tpu t pr odu ced on ex ecu tin g
fu n ction inverse1 w h en th e follow in g in pu t is en ter ed
a s th e v a lu e of v a r ia ble num:
(a )5 (b)0 (c)2 .0 (d)x (e)Non e
def inverse1():
try:
num = input('Enter the number: ')
num = float(num)
inverse = 1.0 / num
except ValueError:
print('ValueError')
except TypeError:
print('TypeError')
except ZeroDivisionError:
print('ZeroDivisionError')
except:
print('Any other Error')
else:
print(inverse)
finally:
print('Function inverse completed')
8 . Ex a m in e th e follow in g fu n ction per cen ta g e:
def percentage(marks, total):
try:
percent = (marks / total) * 100
except ValueError:
print('ValueError')
except TypeError:
print('TypeError')
except ZeroDivisionError:
print('ZeroDivisionError')
except:
print('Any other Error')
else:
print(percent)
finally:
print('Function percentage completed')
Deter m in e th e ou tpu t for th e follow in g fu n ction ca lls:
1 . percentage(150.0, 200.0)
2 . percentage(150.0, 0.0)
3 . percentage('150.0', '200.0')
9 . Iden tify tw o ex ception s th a t m a y be r a ised w h ile
ex ecu tin g th e follow in g sta tem en t:
result = a + b
1 0. Wh a t w ill be th e ou tpu t for th e follow in g code sn ippets
if th e file bein g open ed does n ot ex ist:
1 . try:
f = open('file1.txt', 'r')
except IOError:
print('Problem with Input
Output...\n')
else:
print('No Problem with Input
Output...\n')
2 . try:
f = open('file1.txt', 'w')
except IOError:
print('Problem with Input
Output...\n')
else:
print('No Problem with Input
Output...\n')

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy