Professional Documents
Culture Documents
UNIT-III
CHAPTER-II
EXCEPTION HANDLING
Introduction:
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.
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
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
#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
"""
"""
Output While Running the Program
*************************************
Exception Description= cannot import name
'datetime' from 'time' (unknown location)
Exception Type= (<class 'ImportError'>,
"""
Input and Output
****************
Output when file file name as raj.py,In which may not available
Enter File Nameraj.py
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.
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).
"""
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
"""
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:
Testcase 2:
"""
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
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
"""
Input and Output:
*****************
Test Case 1:
Test case 2:
#Calling Function
print("Current Month=",getMonth())
"""
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.