Exception Handling
Exception Handling
• Errors are the problems in a program due to which the program will stop
the execution.
Page 1 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Page 2 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
COMMON EXCEPTIONS:
• ZeroDivisionError: Occurs when a number is divided by zero.
• EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
Page 3 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Page 4 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE:
Page 5 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
RAISE AN EXCEPTION:
• x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
• x = "hello"
Page 6 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print "a/b result is 0"
else:
print c
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
OUTPUT:
-5.0
a/b result is 0
Page 7 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
ASSERTION IN PYTHON
• In testing code.
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Average of mark1:",avg(mark1))
Page 8 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Using assert with Error Message
LOGGING AN EXCEPTION
Page 9 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
• Logging module provides a set of functions for simple logging and for
following purposes
DEBUG
INFO
WARNING
ERROR
CRITICAL
Page 10 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Logging Variable Data:
dynamic information from application in the logs.
import logging
name = 'John‘
logging.error('%s raised an error', name)
ERROR:root:John raised an error
Displaying Date/Time For Python Logging:
• logging.basicConfig(format=’%(asctime)s %(message)s’)
FILE IN PYTHON
• A file is a chunk of logically related data or information
which can be used by computer programs.
• Files on most modern file systems are composed of three
main parts:
• Header: metadata about the contents of the file (file name,
size, type, and so on)
• Data: contents of the file as written by the creator or editor
Page 11 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY