SlideShare a Scribd company logo
1 of 20
Unit 3
Python Exception handling
06-04-2022 meghav@kannuruniv.ac.in 1
Python Errors and Exceptions
• Encountering errors and exceptions can be very frustrating at times,
and can make coding feel like a hopeless endeavor.
• However, understanding what the different types of errors are and
when you are likely to encounter them can help a lot.
• Python Errors can be of three types:
1.Compile time errors (Syntax errors)
2.Runtime errors (Exceptions)
3.Logical errors
06-04-2022 meghav@kannuruniv.ac.in 2
• Compile time errors (Syntax errors)
• Errors caused by not following the proper structure (syntax) of the
language are called syntax or parsing errors.
• Runtime errors (Exceptions)
• Exceptions occur during run-time.
• Your code may be syntactically correct but it may happen that during
run-time Python encounters something which it can't handle , then it
raises an exception.
06-04-2022 meghav@kannuruniv.ac.in 3
• Logical errors
• Logical errors are the most difficult to fix.
• They occur when the program runs without crashing, but produces
an incorrect result.
• The error is caused by a mistake in the program's logic .
• You won't get an error message, because no syntax or runtime error
has occurred.
06-04-2022 meghav@kannuruniv.ac.in 4
Python Exception Handling
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The finally block lets you execute code, regardless of the result of the
try- and except blocks.
• When an error occurs, or exception as we call it, Python will normally
stop and generate an error message.
06-04-2022 meghav@kannuruniv.ac.in 5
Python Exception Handling
• These exceptions can be handled using the try statement:
• Example
• The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
06-04-2022 meghav@kannuruniv.ac.in 6
• Since the try block raises an error, the except block will be
executed.
• Without the try block, the program will crash and raise an
error:
Example
• This statement will raise an error, because x is not defined:
print(x)
06-04-2022 meghav@kannuruniv.ac.in 7
Example:
try:
a=int(input(“First Number:”))
b=int(input(“Second number”))
result=a/b
print(“Result=”,result)
except ZeroDivisionError:
print(“Division by zero”)
else:
print(“Successful division”)
Output
First Number:10
Second number:0
Division by zero
06-04-2022 meghav@kannuruniv.ac.in 8
Except clause with multiple exceptions
try:
a=int(input(“First Number:”))
b=int(input(“Second Number:”))
result=a/b
print(“Result=”,result)
except(ZeroDivisionError, TypeError):
print(“Error occurred”)
else:
print(“Successful Division”)
Output
First Number:10
Second Number:0
Error occured
06-04-2022 meghav@kannuruniv.ac.in 9
try......finally
• A finally block can be used with a try block
• The code placed in the finally block is executed no matter Exception is
caused or caught
• We cannot use except clause and finally clause together with a try block
• It is also not possible to use else clause and finally together with try block.
Syntax:
try:
suite;
finally:
finally_suite # Executed always after the try block
06-04-2022 meghav@kannuruniv.ac.in 10
Example:
try:
a=int(input(“First Number:”))
b=int(input(“Second number”))
result=a/b
print(“Result=”,result)
finally:
print(“Executed always”)
Output
First Number:20
Second number:0
Executed always
Traceback (most recent call last):
File “main.py”, line 5, in <module>
result=a/b
ZeroDivisionError: integer division or modulo by zero
06-04-2022 meghav@kannuruniv.ac.in 11
Some of the common in-built exceptions are as follows:
1.ZeroDivisionError -Raised when division or modulo by zero takes place for all
numeric types.
2.NameError - Raised when name of keywords, identifiers..etc are wrong
3.IndentationError - Raised when indentation is not properly given
4.IOError - Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that does not exist.
5.EOFError - Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
06-04-2022 meghav@kannuruniv.ac.in 12
Python - Assert Statement
• In Python, the assert statement is used to continue the execute if the given condition
evaluates to True.
• If the assert condition evaluates to False, then it raises the AssertionError exception
with the specified error message.
Syntax
assert condition [, Error Message]
• The following example demonstrates a simple assert statement.
Example:
x = 10
assert x > 0
print('x is a positive number.')
Output
• x is a positive number.
• In the above example, the assert condition, x > 0 evaluates to be True, so it will
continue to execute the next statement without any error.
06-04-2022 meghav@kannuruniv.ac.in 13
• The assert statement can optionally include an error message string, which
gets displayed along with the AssertionError.
• Consider the following assert statement with the error message.
Example: Assert Statement with Error Message
x = 0
assert x > 0, 'Only positive numbers are allowed’
print('x is a positive number.')
Output
Traceback (most recent call last):
assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed
06-04-2022 meghav@kannuruniv.ac.in 14
Python Program for User-defined Exception
Handling:
class YourException(Exception):
def __init__(self, message):
self.message = message
try:
raise YourException("Something is wrong")
except YourException as err:
# perform any action on YourException instance
print("Message:", err.message)
06-04-2022 meghav@kannuruniv.ac.in 15
User-defined Exception Handling:
Example
class Error(Exception):
pass
class ValueTooSmallError(Error):
pass
class ValueTooLargeError(Error):
pass
06-04-2022 meghav@kannuruniv.ac.in 16
Cont..
#Main Program
number=10
while True:
try:
i_num=int(input(“Enter a number:”))
if i_num<number:
raise ValueTooSmallError
elif i_num>number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print(“This value is too small ! Please try again”)
except ValueTooLargeError:
print(“This value is too large! Please try again”)
print(“Congratulations…You guesses it correctly”)
06-04-2022 meghav@kannuruniv.ac.in 17
Logging the exceptions
• Logging is a means of tracking events that happen when some software
runs.
• Logging is important for software developing, debugging, and running.
• To log an exception in Python we can use logging module and through
that we can log the error.
• Logging module provides a set of functions for simple logging and for
following purposes
• DEBUG
• INFO
• WARNING
• ERROR
• CRITICAL
06-04-2022 meghav@kannuruniv.ac.in 18
Logging the exceptions
• 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.
06-04-2022 meghav@kannuruniv.ac.in 19
Example:
06-04-2022 meghav@kannuruniv.ac.in 20
# importing the module
import logging
try:
printf(“Good Morning")
except Exception as Argument:
logging.exception("Error occurred while printing Good Morning")

More Related Content

What's hot

Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaEdureka!
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python TutorialSimplilearn
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Edureka!
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 

What's hot (20)

Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | Edureka
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
OOP Assignment 03.pdf
OOP Assignment 03.pdfOOP Assignment 03.pdf
OOP Assignment 03.pdf
 
Java package
Java packageJava package
Java package
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 

Similar to Python Exception Handling

Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in PythonDrJasmineBeulahG
 
Exception Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptException Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptRaja Ram Dutta
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Edureka!
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingP3 InfoTech Solutions Pvt. Ltd.
 
Exception handling3.pdf
Exception handling3.pdfException handling3.pdf
Exception handling3.pdfBrokeass1
 
Mastering python lesson2
Mastering python lesson2Mastering python lesson2
Mastering python lesson2Ruth Marvin
 
Exception Handling in VB.Net
Exception Handling in VB.NetException Handling in VB.Net
Exception Handling in VB.Netrishisingh190
 

Similar to Python Exception Handling (20)

Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
 
Exception handling
Exception handlingException handling
Exception handling
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
 
Exception Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptException Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.ppt
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Chapter 13 exceptional handling
Chapter 13 exceptional handlingChapter 13 exceptional handling
Chapter 13 exceptional handling
 
Exception handling3.pdf
Exception handling3.pdfException handling3.pdf
Exception handling3.pdf
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
43c
43c43c
43c
 
Mastering python lesson2
Mastering python lesson2Mastering python lesson2
Mastering python lesson2
 
ACP - Week - 9.pptx
ACP - Week - 9.pptxACP - Week - 9.pptx
ACP - Week - 9.pptx
 
Python Session - 6
Python Session - 6Python Session - 6
Python Session - 6
 
Exception Handling in VB.Net
Exception Handling in VB.NetException Handling in VB.Net
Exception Handling in VB.Net
 

More from Megha V

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxMegha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxMegha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMegha V
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expressionMegha V
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data typeMegha V
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7Megha V
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6Megha V
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsMegha V
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Megha V
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3Megha V
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 
Python programming
Python programmingPython programming
Python programmingMegha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplicationMegha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrencesMegha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm AnalysisMegha V
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and designMegha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithmMegha V
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data Megha V
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGLMegha V
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS AutomationMegha V
 

More from Megha V (20)

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Python programming
Python programmingPython programming
Python programming
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
 

Recently uploaded

Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 

Recently uploaded (20)

Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 

Python Exception Handling

  • 1. Unit 3 Python Exception handling 06-04-2022 meghav@kannuruniv.ac.in 1
  • 2. Python Errors and Exceptions • Encountering errors and exceptions can be very frustrating at times, and can make coding feel like a hopeless endeavor. • However, understanding what the different types of errors are and when you are likely to encounter them can help a lot. • Python Errors can be of three types: 1.Compile time errors (Syntax errors) 2.Runtime errors (Exceptions) 3.Logical errors 06-04-2022 meghav@kannuruniv.ac.in 2
  • 3. • Compile time errors (Syntax errors) • Errors caused by not following the proper structure (syntax) of the language are called syntax or parsing errors. • Runtime errors (Exceptions) • Exceptions occur during run-time. • Your code may be syntactically correct but it may happen that during run-time Python encounters something which it can't handle , then it raises an exception. 06-04-2022 meghav@kannuruniv.ac.in 3
  • 4. • Logical errors • Logical errors are the most difficult to fix. • They occur when the program runs without crashing, but produces an incorrect result. • The error is caused by a mistake in the program's logic . • You won't get an error message, because no syntax or runtime error has occurred. 06-04-2022 meghav@kannuruniv.ac.in 4
  • 5. Python Exception Handling • The try block lets you test a block of code for errors. • The except block lets you handle the error. • The finally block lets you execute code, regardless of the result of the try- and except blocks. • When an error occurs, or exception as we call it, Python will normally stop and generate an error message. 06-04-2022 meghav@kannuruniv.ac.in 5
  • 6. Python Exception Handling • These exceptions can be handled using the try statement: • Example • The try block will generate an exception, because x is not defined: try: print(x) except: print("An exception occurred") 06-04-2022 meghav@kannuruniv.ac.in 6
  • 7. • Since the try block raises an error, the except block will be executed. • Without the try block, the program will crash and raise an error: Example • This statement will raise an error, because x is not defined: print(x) 06-04-2022 meghav@kannuruniv.ac.in 7
  • 8. Example: try: a=int(input(“First Number:”)) b=int(input(“Second number”)) result=a/b print(“Result=”,result) except ZeroDivisionError: print(“Division by zero”) else: print(“Successful division”) Output First Number:10 Second number:0 Division by zero 06-04-2022 meghav@kannuruniv.ac.in 8
  • 9. Except clause with multiple exceptions try: a=int(input(“First Number:”)) b=int(input(“Second Number:”)) result=a/b print(“Result=”,result) except(ZeroDivisionError, TypeError): print(“Error occurred”) else: print(“Successful Division”) Output First Number:10 Second Number:0 Error occured 06-04-2022 meghav@kannuruniv.ac.in 9
  • 10. try......finally • A finally block can be used with a try block • The code placed in the finally block is executed no matter Exception is caused or caught • We cannot use except clause and finally clause together with a try block • It is also not possible to use else clause and finally together with try block. Syntax: try: suite; finally: finally_suite # Executed always after the try block 06-04-2022 meghav@kannuruniv.ac.in 10
  • 11. Example: try: a=int(input(“First Number:”)) b=int(input(“Second number”)) result=a/b print(“Result=”,result) finally: print(“Executed always”) Output First Number:20 Second number:0 Executed always Traceback (most recent call last): File “main.py”, line 5, in <module> result=a/b ZeroDivisionError: integer division or modulo by zero 06-04-2022 meghav@kannuruniv.ac.in 11
  • 12. Some of the common in-built exceptions are as follows: 1.ZeroDivisionError -Raised when division or modulo by zero takes place for all numeric types. 2.NameError - Raised when name of keywords, identifiers..etc are wrong 3.IndentationError - Raised when indentation is not properly given 4.IOError - Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. 5.EOFError - Raised when there is no input from either the raw_input() or input() function and the end of file is reached. 06-04-2022 meghav@kannuruniv.ac.in 12
  • 13. Python - Assert Statement • In Python, the assert statement is used to continue the execute if the given condition evaluates to True. • If the assert condition evaluates to False, then it raises the AssertionError exception with the specified error message. Syntax assert condition [, Error Message] • The following example demonstrates a simple assert statement. Example: x = 10 assert x > 0 print('x is a positive number.') Output • x is a positive number. • In the above example, the assert condition, x > 0 evaluates to be True, so it will continue to execute the next statement without any error. 06-04-2022 meghav@kannuruniv.ac.in 13
  • 14. • The assert statement can optionally include an error message string, which gets displayed along with the AssertionError. • Consider the following assert statement with the error message. Example: Assert Statement with Error Message x = 0 assert x > 0, 'Only positive numbers are allowed’ print('x is a positive number.') Output Traceback (most recent call last): assert x > 0, 'Only positive numbers are allowed' AssertionError: Only positive numbers are allowed 06-04-2022 meghav@kannuruniv.ac.in 14
  • 15. Python Program for User-defined Exception Handling: class YourException(Exception): def __init__(self, message): self.message = message try: raise YourException("Something is wrong") except YourException as err: # perform any action on YourException instance print("Message:", err.message) 06-04-2022 meghav@kannuruniv.ac.in 15
  • 16. User-defined Exception Handling: Example class Error(Exception): pass class ValueTooSmallError(Error): pass class ValueTooLargeError(Error): pass 06-04-2022 meghav@kannuruniv.ac.in 16
  • 17. Cont.. #Main Program number=10 while True: try: i_num=int(input(“Enter a number:”)) if i_num<number: raise ValueTooSmallError elif i_num>number: raise ValueTooLargeError break except ValueTooSmallError: print(“This value is too small ! Please try again”) except ValueTooLargeError: print(“This value is too large! Please try again”) print(“Congratulations…You guesses it correctly”) 06-04-2022 meghav@kannuruniv.ac.in 17
  • 18. Logging the exceptions • Logging is a means of tracking events that happen when some software runs. • Logging is important for software developing, debugging, and running. • To log an exception in Python we can use logging module and through that we can log the error. • Logging module provides a set of functions for simple logging and for following purposes • DEBUG • INFO • WARNING • ERROR • CRITICAL 06-04-2022 meghav@kannuruniv.ac.in 18
  • 19. Logging the exceptions • 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. 06-04-2022 meghav@kannuruniv.ac.in 19
  • 20. Example: 06-04-2022 meghav@kannuruniv.ac.in 20 # importing the module import logging try: printf(“Good Morning") except Exception as Argument: logging.exception("Error occurred while printing Good Morning")