You are on page 1of 9

OHM SRI SAIRAM

UNIT-III
CHAPTER-II

EXCEPTION HANDLING

Introduction:

An exception is an unexpected, abnormal or exceptional situation has occurred while


executing program. Various error messages can occur when executing python programs.

An exception is an error that can be handled by a programmer. If the programmer can n’t handle
it, then it will not be an exception, it will become an error.

“An exception is a value (object) that is raised by a function signaling that an unexpected or exceptional
situation has occurred that the function itself cannot handle.”

To handle exceptions, the programmer should perform the following three steps.

Step 1: The programmer should identify the statements where there may be a possibility of
exceptions. Such statements should be written inside ‘try’ block.

A try block looks like as:

try:
#suite of statements

Step 2: The programmer should write the ‘except’ block, where exception is handled and displays
the exception details to the user.

except exceptionname:
#suite of statements

Here “exceptionname” specifies the python standard exception.

Step 3: At last, the programmer should perform cleanup the actions like closing the files and
terminating any other processes which are running. The programmer should write this code in
finally block.

finally:
#suite of statements

PYTHON PROGRAMMING TEACHING HANDOUT Page 1


OHM SRI SAIRAM

#Exception Handling
a=int(input("Enter a"))
b=int(input("Enter b"))
try:
c=a/b
print("Division=",c)
except ZeroDivisionError:
print("Division by zero Exception")
print("Please don't enter denominator as
zero")

"""
Input and Output
****************
Test case 1:
Enter a2
Enter b0
Division by zero Exception
Please don't enter denominator as zero

Test case 2:
Enter a2
Enter b5
Division= 0.4
"""

Various Types of Exceptions:


There are several exceptions available as part of python language that are called built-in
exceptions.
Here some standard exceptions are included in following table.

Exception name Description Example Program


ImportError Raised when an import sys
import try:
statement fails. from time import datetime
except Exception as e:
print("Exception Description=",e)
print("Exception Type=",sys.exc_info())

"""
Output While Running the Program
*************************************
Exception Description= cannot import name
'datetime' from 'time' (unknown location)
Exception Type= (<class 'ImportError'>,

PYTHON PROGRAMMING TEACHING HANDOUT Page 2


OHM SRI SAIRAM

ImportError("cannot import name 'datetime' from 'time'


(unknown location)")
, <traceback object at 0x00000196D4B01700>)
IndexError Raised when a >>> l=[1,2,3]
sequence index >>> l[5]
is an out of Traceback (most recent call last):
range. File "<pyshell#1>", line 1, in <module>
l[5]
IndexError: list index out of range
NameError Raised when a >>> name
local or global Traceback (most recent call last):
name not found. File "<pyshell#7>", line 1, in <module>
name
NameError: name 'name' is not defined
TypeError Raised when an >>> 2+'3'
operation or Traceback (most recent call last):
function is File "<pyshell#5>", line 1, in <module>
applied to an 2+'3'
object of TypeError: unsupported operand type(s) for +: 'int' and 'str'
inappropriate
type.
ValueError Raised when a #ve.py
built-in a=int(input("enter a="))
operation or print("a=",a)
function is
applied to an Exception occurred while compiling program
inappropriate **********************************************
value Enter a=2.89
Traceback (most recent call last):
File "F:/BHAVAPYTHON/WEEK12/exception2.py", line 1, in
<module>
a=int(input("enter a"))
ValueError: invalid literal for int() with base 10: '2.89'
IOError Raised when an #Demonstration of IOError to open a file which does n't exist
input/output import sys as s
operation fails. try:
name=input("Enter File Name")
f=open(name,'r')
except IOError as i:
print("Exception description=",i)
print("file Not Found”, name)
print("Exception information=",s.exc_info())

"""
Input and Output
****************
Output when file file name as raj.py,In which may not available
Enter File Nameraj.py

PYTHON PROGRAMMING TEACHING HANDOUT Page 3


OHM SRI SAIRAM

Exception description= [Errno 2] No such file or directory:


'raj.py' file Not Found raj.py
Exception information=(<class 'FileNotFoundError'>,
FileNotFoundError(2, 'No such file or directory'),
<traceback object at 0x0000021408726700>)
"""
ZeroDivisionError Raised when the *** Example shown in above program
denominator is
zero in a division
or modulus
operation.

Propagation of Raised Exceptions:

Raised exceptions are not required to be handled in Python.

When an exception is raised and not handled by the client code, it is automatically
propagated back to the client’s calling code (and its calling code, etc.) until handled. If an
exception is thrown all the way back to the top level (main module) and not handled, then
the program terminates and displays the details of the exception.

Propagation of Exception

An exception is either handled by the client code, or automatically propagated back to the
client’s calling code, and so on, until handled. If an exception is thrown all the way back to the
main module (and not handled), the program terminates displaying the details of the exception.

Catching and Handling Exceptions:


Many of the functions in the python standard library raise exceptions.
For Example, the factorial function of the python module raises a ValueError exception when a
negative value is passed to it.

PYTHON PROGRAMMING TEACHING HANDOUT Page 4


OHM SRI SAIRAM

import math as m
import sys
n=int(input("Enter n="))
try:
print("Factorial of n=",m.factorial(n))
except ValueError:
print("Can not compute the factorial of a number")
print("Exception information=",sys.exc_info())

"""
Input and Output
****************
Test case 1:
Enter n=2
Factorial of n= 2

Test case 2:

Enter n=-2
Can not compute the factorial of a number
Exception information= (<class 'ValueError'>,
ValueError('factorial() not defined for negative values'),
<traceback object at 0x000001BE9B0F1700>)

"""

The call to the factorial function is contained within a try suite ( try block )—the block of
code surrounded by try and except headers. The suite following the except header is referred to as
an exception handler. This exception header “catches” exceptions of type ValueError.

Exceptions are caught and handled in Python by use of a try suite (try block) and exception
handler(using except or finally suite).

PYTHON PROGRAMMING TEACHING HANDOUT Page 5


OHM SRI SAIRAM

Modified version of above Program:


import math as m
import sys
n=int(input("Enter n="))
valid_input=False
while not valid_input:
try:
print("Factorial of n=",m.factorial(n))
valid_input=True
except ValueError:
print("Can not compute the factorial of a number for
negative numbers")
n=int(input("Re-enter n again="))

"""
Input and Output
****************
Enter n=-2
Can not compute the factorial of a number of for negative
numbers
Re-enter n again=-4
Can not compute the factorial of a number of for negative
numbers
Re-enter n again=25
Factorial of n= 15511210043330985984000000
"""

PYTHON PROGRAMMING TEACHING HANDOUT Page 6


OHM SRI SAIRAM

Exception handling and User Input:

In python programming, various exceptions are raised by built-in functions. In some other
different cases, programmer defined functions may raise exceptions.

The above is explained through following user defined function getMonth(). This function
reads month number as input, value in the numeric range of 1-12. If the user enters non numeric
character or outside the range 1-12, it raises ValueError.

#raiseexception.py
#Raise Exception by User defined function
def getMonth():
month=int(input("Enter current month(1-12)="))
if month <1 or month >12:
raise ValueError("Invalid Month Value")
return month

#Calling Function
print("Current Month=",getMonth())

"""
Input and Output
*****************
Testcase 1:

Enter current month(1-12)=7


Current Month= 7

Testcase 2:

Enter current month(1-12)=22


Traceback (most recent call last):
File "F:/BHAVAPYTHON/WEEK12/raiseexception.py", line 9, in
<module>
print("Current Month=",getMonth())
File "F:/BHAVAPYTHON/WEEK12/raiseexception.py", line 5, in
getMonth
raise ValueError("Invalid Month Value")
ValueError: Invalid Month Value

"""

Programmer - defined functions may raise exceptions in addition to the exceptions raised
by built-in functions of python.

cxgfxfgxf
PYTHON PROGRAMMING TEACHING HANDOUT Page 7
OHM SRI SAIRAM

Exception Handling and File Processing:

In general, while handling operations with files, when opening a file for reading, an
exception is raised if the file can n’t found. In this case, the standard IOError exception raised and
the program terminates with a ‘No such file or directory’ error message.

IOError exceptions raised as a result of a file open error can be caught and handled.
Sample Program demonstrates exception while opening file

#Exception handling of Open File Error


fname=input("Enter File Name=")
file_opened=False
while not file_opened:
try:
file=open(fname,'r')
file_opened=True
l=file.read()
print("File Contents:")
print(l)
except IOError:
print("File open error")
fname=input("Re-enter Filename=")

"""
Input and Output:
*****************
Test Case 1:

Enter File Name=notopened.py


File open error
Re-enter Filename=againopen.py
File open error
Re-enter Filename=exception2.py
File Contents:
a=int(input("enter a"))
print("a=",a)

Test case 2:

Enter File Name=raiseexception.py


File Contents:
#Raise Exception by User defined function
def getMonth():
month=int(input("Enter current month(1-12)="))
if month <1 or month >12:
raise ValueError("Invalid Month Value")
return month

#Calling Function
print("Current Month=",getMonth())
"""

PYTHON PROGRAMMING TEACHING HANDOUT Page 8


OHM SRI SAIRAM

In the above program, if the file name entered available in the current working directory,
file opened and contents from file is read and displayed.

Suppose if file name entered not available, “IOError” exception raised and asks to reenter
the file again. This process continues and while loop iterated until entered filename available in
the current working directory.

PYTHON PROGRAMMING TEACHING HANDOUT Page 9

You might also like