Chapter 6 - Exception Handling
Chapter 6 - Exception Handling
C h a pt e r
6
In This Chapter
6.1 Introduction
6.3 Concept of
6.2 Exceptions and Exceptiorn Handling
Exception Handling 6.4 Exception Handling in Python
6.1 Introduction
When you create and develop programs, errors occur naturally. Sometimes, you misspell a
very
name or keyword, or sometimes you unknowingly change the symbols. These are not that
easy and errors are
Common and easy to handle errors. But programming is not that
language developers have
Simple. So, to handle virtually any type of errors that may occur,
Python also supports a specific and
Created numerous ways to catch and prevent them.
errors of any type that may occur. This
well-defined mechanism of catching and preventing
nechanism is known as Exception Handling. In
this chapter you are going to learn about
techniques in Python, different types of errors that may occur and ways to
GACePion handling
avoid them.
265
Chapter
COMPUTER SCIENCE WITH
266 PYTHON - XIl
>>>print (3/0)
If you execute above code, youll receive an error message as:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print 3/0
ZeroDivisionError: integer division or modulo by zero Unh
Chapter 6: EXCEPTION HANDLING
267
This message 1s generated by default
handler does the following upon exception handler of Python. The default
occurrence of an
exception
(i) Prints out exception Exception :
(ii) Prints the stack trace,description
ie., hierarchy of methods where the
(iii) Causes the program to exception occurred
terminate.
6.3 Concept of Exception Handling
The global concept of error-handling is pretty
simple. That is, write your code in such a way
that it raises some error flag every time something
goes wrong. Then trap this error flag and if
this is spotted, call the error handling routine. The intended
like the one shown in Fig. 6.1.
program flow should be somewhat
The raising of imaginary
error flag is called throwing 3
or raising an errTOr. When an Write code
. Such that it Gall
error is thrown, the overall raises an 2| the
error-flag every If error flag Error
system responds by catching time something handiing
the error. And surrounding a goes wrong
is raised then routine
block of error-sensitive
throw exception catch eXception
code-with-exception-handling
is called trying to execute a
Figure 6.1 Concept of exception handling.
block.
Some terminology used within exception handling follows.
Description Python Terminology
An unexpected error that occurs during runtime Exception
A set of code that might have an exception thrown in it. try block
The process by which an exception is generated and passed Throwing or raising an error
to the program.
Capturing an exception that has just occurred and executing Catching
statements that try to resolve the problem
The block of code that attempts to deal with the exception except clause or exceptlexception
block or catch block
(ie., problem).
Stack trace
The sequence of method calls that brought control to the
point where the exception occurred.
NoTE
Unhandled exceptions will cause Python to halt
execution.
COMPUTER SCIENCE
WITH
268 pUIHON
Handling in Python
6.4 Exception and except clauses in the
wherein the
Exception code that
Handling in
whenthe
Python involves the
use of try
handling exception
See below:
following code:
For instance, consider the
try :
try:
X= int ("XII")
except:
print ("Error converting 'XII toa
number")
The output generated from above
code is not the usual error now, it
is :
Error converting 'XII' to a number
Consider program 6.1 that is expanded version of the above example. It terror-checks auser's
input to make sure an
integer is entered.
HANDLING
269
EXCEPTION
Chopter6
6.4.1
General Built-in Python Exceptions
In this section, we are discussing about some built-in exceptions of Python. The built-in
exceptions can be generated by the interpreter or built-in functions. Some common built-in
exceptions in Python are being listed below in Table 6.1.
able 6.1 Some built-in Exceptions
except:
print ("Error opening file")
The above program will open the file successfully if the file Error opening file
myfile.trt exists and contains some data otherwise it shows an
output as :
But the above code did not tell which caused the error.
The except clause can then use this additional argument to print the associated error-message of
this exception as : str (exArgument). Following code illustrates it :
try:
print ("result of 10/5 =", (10/5) )
print ("result of 10/0 =", (10/0) ) Notice second argument to except block i.e., e
except ZeroDivisionError as e: here - gets reference of raised exception
print ("Exception ", str(e)) Printing standard error message of raised
exception through the second argument
The above code will give output as:
result of 10/5 = 2.0
EXception - division by zero The mesage associated with the exception
try:
#:
except <exceptionName1> :
#:
except <exceptionName2> :
#:
except : The except block without any
will handle the
rest of the exception nam
exceptions
else :
*Tfthere is no
exceptionthen the statements in this
block get executed.
kolso :clause willexecute if
there is no
Vou want to
execute when
no exceptions get exception raised, so you may put your code that
raised. Following programn6.3 illustrates the same.
6.3 Program to handle multiple exceptions.
try:
Irogram
my_file =open("myfile.txt")
my_ line =my_file.readline()
my_int = int(s.strip() )
my_calculated_value = 101/my_ int
except IOError: These three except blocks will catch and
handle tOError, ValueError and
print ("I/0 error occurred") ZeroDivisionError exceptions respectivety
except ValueError:
print ("Could not convert datato an integer.")
except ZeroDivisionError : +
print ("Division by zero error")
except: The unnamed except block will
handle the rest of the exceptions
print ("Unexpected error:")
else :
print ("Hurray! No exceptions !") This last else: block will get executed
if no exception is raised
The output produced by above code is :
I/0 error occurred
272
You can alsouse
finally afinally: block along
Block with a try: block, just like you use except: Jlock,eg,%,
6.4.4 The
exception
try:
statements that may raise
#
[except:
exception here]
# handle
finally: run
that will always
# statements block is that:
between an except: block and the finally: the finally: block
The difference
that contains any code that must execute, whether the try: block raised an exception or n
isaplats.
For example,
try:
"r+")
fh =open("poems. txt", This statement will always be
fh.write("Adding new line") executed in the end
finally:
data")
print ("Error: can\'t find file or read
You may combine finally: with except: clause. In such a combination, the except: block will ge
executed only in case an exception is raised and finally: block will get executed ALWAYS,0n
the end. Following code illustrates it:
try:
fh =open("poem1.txt", "r")
print (fh. read())
except:
print ("Exception Occurred")
finally:
print ("Finally saying goodbye.")
The output produced by above code will be :
Exception Occurred This is printed because except: block
This is printed because got executed when exception occurred.
finally: block got executed
in the end. Finally saying goodbye
In the above code if no exception is raised, still the above
code will print :
Finally saying goodbye
because finally : block gets executed always in the
end.
6.4.5 Raising/Forcing an Exception
In Python, you can use the raise
keyword to raise/force an exception. That
programmer can force an exception meo
message to your exception handling tomodule.
occur through raise keyword. It can also pass
raise <exception> (<message>) For example:
The exception raised in this way should be apre-defined Built-in exception. Consider following
code snippet that forces a ZeroDivisionError exception to occur without actually dividing&
value by zero :
EXCEPTION HANDLING
try:
273
a= int(input ("Enter numerator :")) Notice this raise
b= int (input ("Enter built-in exception statement is raising
ifb ==0:
denominator :") ZeroDivisionError
with a custom message,
that followS
the exception name
naise
ZeroDivisionError (str(a) +"/0 not
print (a/b)
possible")
except ZeroDivisionError as e:
print ("Exception", str(e))
The output produced by above code is :
Enter n u m e r a t o r : 7
LET US REVISE
anomalous situations in
a program.run is
known as exception handling.
Way of handling take place.
enclosing the code wherein exceptions can
The try block is for handles it.
The except block traps the exception and
4
exception.
The raise keyword forces an
of Exceptionclass.
All exceptions are subclasses
275
running properly put
producing
condition occurring during wrong output is an exception. False
program
A rare
Unexpected
Asertion. Exception handling is responsible for handling anomalous situations during the
execution of a program.
(c)
Reason. Exception handling handles all types of errors and exceptions.
2Asertion. Exception handling code is separate from normal code. (a)
Keason. 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. (a)
Keason. The code where unexpected runtime exception may occur is separate from the codewhere
the action takes place when an exception occurs.
eruon. No matter what exception occurs, you can always make sure that some common action
takes place for all types of
exceptions. (a)
Reason. The finally block Contains the code that must execute.
NOTE :
Answers for 0T0s are given at the end of the book.
Slhed Prohlem
1,
What is an
Exception ?
Solution. Exception in general refers to some contradictory or unusual situation which can be
encountered while executing a program.
COMPUTER SCIENCE \WITH
276
Handling required ?
2 When is Exception handling is ideal
for :
exception
Solution. The
processing exceptional situations
components that cannot
handle
them directly
exceptions for that should not process
processing components
" for widely used
processing exceptions
exceptions error-processing.
try:
x= float (input ("Your number:"))
inverse =1.0/x
except ValueError:
print ("You should have given either an int or a float")
except ZeroDivisionError:
print ("Infinity")
finally:
print ("There may or may not have been an exception. ")
Solution.
(a) There may or may not have been an exception.
(b) Infinity
There may or may not have been an exception.
(c) There mayor may not have been an exception.
(d) Youshould have given either an int or a float
There may or may not have been an exception.
7. What is the purpose of the finally clause of a
try-catch-finally statement ? whetheren
) import mymodule
() divide("2", "1")
executing finally clause
Traceback (most recent call last):
line 1, in <module>
File "<pyshell#46>",
divide("2", "1")
divide
File "C:/test16..py", line 22, in
result= X/y 'str' and'str'
type(s) for/:
TypeError: unsupported operrand
COMPUTER
SCIENCE
278 MITH
PrTHOH
GUIDELINES TO NCERT
QUESTIONS
Python
NCERT
1: Exception Hondling in
NCERT Chapter be a syntar
error is an cxception but
every exception
cannot error."
Justify the
1. "Every syntax
means occurrence of some
unexpected Syntaxevent.
error occurs Sateme
hence can be
Ans. An exception is unexpected event and termed
violated, which
language rules are unexpected event causing
However,exception means occurrence of
time only.
program
syntax errors are caught during compile
runtime, while every exception cannot be a
"every syntax error is an exception but syntax erro0r."
Hence to
exceplions raised ? Give
examples support your ansuwers.
2. hen are the tollowing buill-in (c) NameError (d) ZeroDivisionError
(b) IOError
(a) ImportError
examples of these
Ans. For exception details,
refer to Table 6.1. For exceptions
:
(a) Refer to Q. 8(c)
(b) Refer to Q. 8(g)
(c) Refer to Q. 8/d)
(d) Refer to Q.8(b)
numbers
3. What is the usc of a raise statement ? Write a code to accept two and display the
Appropriate exception should be raised if the user enters the second number (denominator) ootn
Ans.
The raise keyword is used to manually raise arn exception like exceptions are raised hr Bd
itself.
a = int( input("Enter value for a :"))
b= int( input("Enter value for b :"))
try:
if b == 0:
raise ZeroDivisionError # raising exception using raise keyword
print (a/b)
except ZeroDivisionError:
print("Please enter non-zero value for b. ")
4. Use assert statement in Question No. 3 to test the
division expression in the progrul.
Ans.
a= int(input("Enter value for a
:"))
b= int(input("Enter value for
b:"))
assert b!=0, "Value for b must
be non-zero"
print(a/b)
7. Consider the code given
below and fill in the blanks.
print ("Learning Exceptions. ..")
try:
num1 = int(input ("Enter
the first number)
num2 = int(input ("Enter
the second number"))
EXCEPTION HANDLING
279
quotient= (hum1/num2)
correct")
# toenter only integers
print(""Please enter only numbers")
e x c e p t
except
# Denominator should not be zero
print(
"Number 2should not be zero")
else:
print(
"Great you are a good programmer")
# to be éxecuted at the end
print("JOB OVER... GO GET SOME REST")
Ans.
import math
print ("Code to test wrong TYPE of arguments")
try:
number"))
numl = int (input ("Enter the first
result1 =math.sqrt(num1)
print ("Sqrt:", result1) integers
except ValueError: # to enter only
numbers")
enter only
print ("Please
t tobe executed at the end
finally:
types; Wrong no, of requires requires
print ("Tested only wrong *
args")
of arquments
Code to test wrong TYPE
number-9
Enter the first
Positive numbers
Please enter only
numberk
Enter the second
Please enter only numbers
requires *aras
Tested only wrong types; Wrong no. of requires
Code to test wrong TYPE of arquments
Enter the first number6
Sgrt: 2.449489742783178
Enter the second number4
POw: 1296.0
Tested only wrong types; Wrong no. of requires requires *args
9. What is the use of finally clause ? Use finally clause in the problem given in
Question No
Ans. Refer to section 6.4.4.
GLOSSARY
Exception An onomalous situation encountered by
the program.
Syntax error Programming language's grammar rules violation error.
Compile time errorError that the compiler/interpreter
Run time error
can find during compilation.
Error during program execution.
Assisnment
1. What is exception ?
What is exception handling ?
2. Why is exception
3. How do you raise handling necessary ?
an exception? Give
4. How do you code example.
handle an exception in
5. Describe the Python ?
keyword try. What is the
6. Predict the
output by following code : role of try block?
import math
def f(x):
if x<=0:
raise ValueError(f: argument
must be greater
return math.sqrt(x)+2than zero)
:EXCEPTION HANDLING
281
d e f g ( x ) :
y=f(x)
print (y >2)
try:
g(1)
g(-1)
except Exception, e:
print Exception', e.message
Which of the following two codes will print "File does not exist"
ifthe file being opened does not exiSt
if filename != " ":
() (b) try:
f= open(filename, 'r)
f=open(filename, ')
else:
except IOError:
print ("file does not exist") print ("file does not exist")
8IWhich of the following four outputs is produced by the code that follows ?
output 1:
-2 -1
-1 -1
0integer division or modulo by zero
output 2 :
-2 -1
-1 -1
0integer division or modulo by zero
11
20
output 3 : output 4 :
-2 -2 -1
-0.5 -1 -1 -1
-1.0 0 0 Exception occurred
division by zero
1.0 2
0.5
Given code is :
for x in range(-2, 3) :
print (x, sep =""),
try:
print (1/x, end =" ")
except ZeroDivisionError as e :
print (str(e) )
except :
print ("Exception occurred")
COMPUTER SCIENCE WITH
282
PYIHON -
following code fragments
:
9 Find the errors in
(a) try:
fs = open ("/notthere")
exception IOError: gracefully")
print ("The file does
not exist,exiting
always print")
print ("This line will
(b) try:
fh = open("abc. txt")
try:
fhl = open ("newl.txt", "r")
except ValueError:
gracefully")
print ("The file does not exist, exiting
(c) def ret ():
sqrs = [ x**2 for x in range(1, 10) ]
i =0
w.ile True :
return sqrs[i]
i+=1
c= ret().next()
10. Write a function read a Time class object storing hours and minutes. Raise a user-defined error if values
other than 0..23 is entered for hours and other than 0.59 is entered for minutes.
11. Write a program to read details of student for result
preparation.
exception-handling codes such as ValueError, IndexError, ZeroDivisionError,Incorporate all possible
user-defined exceptions
etc.