0% found this document useful (0 votes)
12 views11 pages

Exception Handling

The document discusses exception handling in Python, outlining two types of errors: syntax errors and logical errors (exceptions). It details common exceptions, how to raise exceptions, and the use of assertions for testing conditions in code. Additionally, it covers logging exceptions for diagnostic and audit purposes, including the use of the logging module to track events and errors.

Uploaded by

www.ananya5002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views11 pages

Exception Handling

The document discusses exception handling in Python, outlining two types of errors: syntax errors and logical errors (exceptions). It details common exceptions, how to raise exceptions, and the use of assertions for testing conditions in code. Additionally, it covers logging exceptions for diagnostic and audit purposes, including the use of the logging module to track events and errors.

Uploaded by

www.ananya5002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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
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.

• 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
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:

• 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 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

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.

Page 7 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
ASSERTION IN PYTHON

• An Assertion in Python or a Python Assert Statement is one which asserts


(or tests the trueness of) a condition in your code. This is a Boolean
expression that confirms the Boolean output of a condition.

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 8 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Using assert with Error Message

LOGGING AN EXCEPTION

• Logging, in software applications, is a way to track events. Before we can


proceed, telling you more about it, we want to exemplify.

• To log an exception in Python we can use logging module and through


that we can log the error.

• Logging an exception in python with an error can be done in the logging.


exception() method. This function logs a message with level ERROR on
this logger. The arguments are interpreted as for debug(). Exception info
is added to the logging message. This method should only be called from
an exception handler

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
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

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.error(), logging.exception(), or logging.critical() report the


suppression of an error without raising an exception.

# importing the module


import logging
try:
printf(“Hello")
except Exception as Argument:
logging.exception("Error occured while printing Hello")
ERROR:root:Error occured while printing GeeksforGeeks Traceback (most
recent call last): File "/home/gfg.py", line 3, in printf("GeeksforGeeks")
NameError: name 'printf' is not defined
We can also log the error message into different file without showing error
in the console by the following method:

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

You might also like