SlideShare a Scribd company logo
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")
Ad

More Related Content

What's hot (20)

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 : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Kamal Acharya
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
baabtra.com - No. 1 supplier of quality freshers
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
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!
 
Lesson 02 python keywords and identifiers
Lesson 02   python keywords and identifiersLesson 02   python keywords and identifiers
Lesson 02 python keywords and identifiers
Nilimesh Halder
 
Python for loop
Python for loopPython for loop
Python for loop
Aishwarya Deshmukh
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Kamal Acharya
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
Explore Skilled
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
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!
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
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!
 
Lesson 02 python keywords and identifiers
Lesson 02   python keywords and identifiersLesson 02   python keywords and identifiers
Lesson 02 python keywords and identifiers
Nilimesh Halder
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
Explore Skilled
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 

Similar to Python Exception Handling (20)

Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
sarthakgithub
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptxException handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
Exception handling.pptxnn h
Exception handling.pptxnn                                        hException handling.pptxnn                                        h
Exception handling.pptxnn h
sabarivelan111007
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
gandra jeeshitha
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
wulanpermatasari27
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
Inzamam Baig
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
DrJasmineBeulahG
 
Introduction to Python Prog. - Lecture 3
Introduction to Python Prog. - Lecture 3Introduction to Python Prog. - Lecture 3
Introduction to Python Prog. - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
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
Raja Ram Dutta
 
Exception-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdfException-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
Exception-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdfException-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception Handling in Python Programming.pptx
Exception Handling in Python Programming.pptxException Handling in Python Programming.pptx
Exception Handling in Python Programming.pptx
vinayagrawal71
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
Faisaliqbal203156
 
lecs101.pdfgggggggggggggggggggddddddddddddb
lecs101.pdfgggggggggggggggggggddddddddddddblecs101.pdfgggggggggggggggggggddddddddddddb
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
Exception handling
Exception handlingException handling
Exception handling
Sandeep Rawat
 
Chapter 13 exceptional handling
Chapter 13 exceptional handlingChapter 13 exceptional handling
Chapter 13 exceptional handling
Praveen M Jigajinni
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptxException handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
DrJasmineBeulahG
 
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
Raja Ram Dutta
 
Exception-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdfException-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
Exception-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdfException-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception Handling in Python Programming.pptx
Exception Handling in Python Programming.pptxException Handling in Python Programming.pptx
Exception Handling in Python Programming.pptx
vinayagrawal71
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
lecs101.pdfgggggggggggggggggggddddddddddddb
lecs101.pdfgggggggggggggggggggddddddddddddblecs101.pdfgggggggggggggggggggddddddddddddb
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
Ad

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
Megha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
Megha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Megha V
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
Megha 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 type
Megha V
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
Megha V
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha 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 3
Megha V
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
Megha V
 
Python programming
Python programmingPython programming
Python programming
Megha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
Megha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
Megha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
Megha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
Megha 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 OpenGL
Megha V
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
Megha V
 
Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
Megha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
Megha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Megha V
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
Megha 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 type
Megha V
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
Megha V
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha 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 3
Megha V
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
Megha V
 
Python programming
Python programmingPython programming
Python programming
Megha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
Megha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
Megha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
Megha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
Megha 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 OpenGL
Megha V
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
Megha V
 
Ad

Recently uploaded (20)

Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 

Python Exception Handling

  • 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 15
  • 16. User-defined Exception Handling: Example class Error(Exception): pass class ValueTooSmallError(Error): pass class ValueTooLargeError(Error): pass 06-04-2022 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 19
  • 20. Example: 06-04-2022 [email protected] 20 # importing the module import logging try: printf(“Good Morning") except Exception as Argument: logging.exception("Error occurred while printing Good Morning")