EXCEPTION HANDLING IN PYTHON
• Errors are the problems in a program due to which the program will stop
the execution.
Two types of Error occurs in python.
• Syntax errors(parsing errors)
• Logical errors (Exceptions)
• An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program's instructions. In general,
when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an
error.
Page 1 of 25 Page 2 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
COMMON EXCEPTIONS:
• ZeroDivisionError: Occurs when a number is divided by zero.
• NameError: It occurs when a name is not found. It may be local or
global.
• IndentationError: If incorrect indentation is given.
• IOError: It occurs when Input Output operation fails.
• EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
Page 3 of 25 Page 4 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE:
RAISE AN EXCEPTION:
• As a Python developer you can choose to throw an exception if a
condition occurs.
• To throw (or raise) an exception, use the raise keyword.
• We can use raise to throw an exception if a condition occurs. The
statement can be complemented with a custom exception.
• x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
• x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
# Program to depict else clause with try-except
# Function which returns a/b
Page 5 of 25 Page 6 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
def AbyB(a , b): ASSERTION IN PYTHON
try:
c = ((a+b) / (a-b)) • An Assertion in Python or a Python Assert Statement is one which asserts
except ZeroDivisionError: (or tests the trueness of) a condition in your code. This is a Boolean
print "a/b result is 0" expression that confirms the Boolean output of a condition.
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
USER DEFINED EXCEPTION
• Programmers may name their own exceptions by creating a new exception
class. Exceptions need to be derived from the Exception class, either
directly or indirectly. Where Assertion in Python used?
• In checking types/ in checking valid input.
• In checking values of arguments.
• Checking outputs of functions.
• As a debugger to halt where an error occurs.
• In testing code.
• In detecting abuse of an interface by another programmer.
Using assert without Error Message:
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Average of mark1:",avg(mark1))
Page 7 of 25 Page 8 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Using assert with Error Message • Logging module provides a set of functions for simple logging and for
following purposes
DEBUG
INFO
WARNING
ERROR
CRITICAL
PYTHON LOGGING FUNCTIONS
• logging.info() or logging.debug() for the detailed output of events that
occur during normal operation of a program.
• warnings.warn() issues a warning for a runtime event if the issue is
avoidable.
• logging.warning() issues a warning for a runtime event if we need to note
the event even when the client can do nothing about it.
LOGGING AN EXCEPTION
• logging.error(), logging.exception(), or logging.critical() report the
• Logging, in software applications, is a way to track events. Before we can suppression of an error without raising an exception.
proceed, telling you more about it, we want to exemplify.
# importing the module
• To log an exception in Python we can use logging module and through import logging
try:
that we can log the error.
printf(“Hello")
• Logging an exception in python with an error can be done in the logging. except Exception as Argument:
exception() method. This function logs a message with level ERROR on logging.exception("Error occured while printing Hello")
ERROR:root:Error occured while printing GeeksforGeeks Traceback (most
this logger. The arguments are interpreted as for debug(). Exception info
recent call last): File "/home/gfg.py", line 3, in printf("GeeksforGeeks")
is added to the logging message. This method should only be called from NameError: name 'printf' is not defined
an exception handler We can also log the error message into different file without showing error
in the console by the following method:
PURPOSES OF LOGGING IN PYTHON
• Diagnostic Logging- To record events that revolve around the
application’s operation.
• Audit Logging- To record events for business analysis.
Page 9 of 25 Page 10 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY 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