SlideShare a Scribd company logo
Python Certification Training www.edureka.co/python
Python Certification Training www.edureka.co/python
Agenda
Exception Handling In Python
Python Certification Training www.edureka.co/python
Agenda
Introduction 01
Why need Exception
Handling?
Getting Started 02
Concepts 03
Practical Approach 04
What are exceptions?
Looking at code to
understand theory
Process of Exception Handling
Python Certification Training www.edureka.co/python
Why Need Exception Handling?
Exception Handling In Python
Python Certification Training www.edureka.co/python
Why Need Exception Handling?
Dividing by zero
Kid
Programmer
Python Certification Training www.edureka.co/python
Why Need Exception Handling?
Dividing by zero
Beautiful Error Message!
Traceback (most recent call last):
File, line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Python Certification Training www.edureka.co/python
What Is Exception Handling?
Exception Handling In Python
Python Certification Training www.edureka.co/python
What Is Exception Handling?
An exception is an event, which occurs during the execution of a program, that disrupts
the normal flow of the program's instructions
Definition of Exception
Process of responding to the occurrence, during computation, of exceptional conditions requiring
special processing – often changing the normal flow of program execution
Exception Handling
What is an exception?
What is exception handling?
Let us begin!
Python Certification Training www.edureka.co/python
Process of Exception Handling
Exception Handling In Python
Python Certification Training www.edureka.co/python
Process of Exception Handling
Everything is fixable!How?
Handle the Exception
User Finds Anomaly Python Finds Anomaly
User Made Mistake
Fixable?
Yes No
Find Error
Take Caution
Fix Error “Catch”
“Try”
If you can’t,
Python will!
I love Python!
Python Certification Training www.edureka.co/python
Process of Exception Handling
Important Terms
Keyword used to keep the code segment under checktry
Segment to handle the exception after catching itexcept
Run this when no exceptions existelse
No matter what run this code if/if not for exceptionfinally
Python Certification Training www.edureka.co/python
Process of Exception Handling
Visually it looks like this!
Python Certification Training www.edureka.co/python
Coding In Python
Exception Handling In Python
Python Certification Training www.edureka.co/python
Coding In Python
Python code for Exception Handling
>>> print( 0 / 0 ))
File "<stdin>", line 1
print( 0 / 0 ))
^
SyntaxError: invalid syntax
Syntax Error
>>> print( 0 / 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Exception
Python Certification Training www.edureka.co/python
Raising An Exception
We can use raise to throw an exception if a condition occurs
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
Traceback (most recent call last):
File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
Python Certification Training www.edureka.co/python
AssertionError Exception
Instead of waiting for a program to crash midway, you can also start by making an assertion in Python
import sys
assert ('linux' in sys.platform), "This code runs on Linux only."
Traceback (most recent call last):
File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.
Python Certification Training www.edureka.co/python
Try and Except Block
Exception Handling In Python
Python Certification Training www.edureka.co/python
Try And Except Block
The try and except block in Python is used to catch and handle exceptions
def linux_interaction():
assert ('linux' in sys.platform), "Function can only run on Linux systems."
print('Doing something.')
try:
linux_interaction()
except:
pass
Try it out!
Python Certification Training www.edureka.co/python
Try And Except Block
The program did not crash!
try:
linux_interaction()
except:
print('Linux function was not executed')
Linux function was not executed
Python Certification Training www.edureka.co/python
Function can only run on Linux systems.
The linux_interaction() function was not executed
Try And Except Block
Example where you capture the AssertionError and output message
try:
linux_interaction()
except AssertionError as error:
print(error)
print('The linux_interaction() function was not executed')
Python Certification Training www.edureka.co/python
Could not open file.log
Try And Except Block
Another example where you open a file and use a built-in exception
try:
with open('file.log') as file:
read_data = file.read()
except:
print('Could not open file.log')
If file.log does not exist, this block of code will output the following:
Python Certification Training www.edureka.co/python
Exception FileNotFoundError
Raised when a file or directory is requested but doesn’t exist.
Corresponds to errno ENOENT.
Try And Except Block
In the Python docs, you can see that there are a lot of built-in exceptions that you can use
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
[Errno 2] No such file or directory: 'file.log'
If file.log does not exist, this block of code will output the following:
Python Certification Training www.edureka.co/python
Try And Except Block
Another Example Case
try:
linux_interaction()
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
except AssertionError as error:
print(error)
print('Linux linux_interaction() function was not executed')
If the file does not exist, running this code on a Windows machine will output the following:
Function can only run on Linux systems.
Linux linux_interaction() function was not executed
[Errno 2] No such file or directory: 'file.log'
Python Certification Training www.edureka.co/python
Try And Except Block
Key Takeaways
• A try clause is executed up until the point where the first exception is
encountered.
• Inside the except clause, or the exception handler, you determine how the
program responds to the exception.
• You can anticipate multiple exceptions and differentiate how the program
should respond to them.
• Avoid using bare except clauses.
Python Certification Training www.edureka.co/python
The else Clause
Exception Handling In Python
Python Certification Training www.edureka.co/python
The else Clause
Using the else statement, you can instruct a program to execute a certain
block of code only in the absence of exceptions
Python Certification Training www.edureka.co/python
The else Clause
Example Case
try:
linux_interaction()
except AssertionError as error:
print(error)
else:
print('Executing the else clause.')
Doing something.
Executing the else clause.
Python Certification Training www.edureka.co/python
The else Clause
You can also try to run code inside the else clause and catch possible exceptions there as well:
try:
linux_interaction()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
Doing something.
[Errno 2] No such file or directory: 'file.log'
Python Certification Training www.edureka.co/python
The finally Clause
Exception Handling In Python
Python Certification Training www.edureka.co/python
The finally Clause
finally is used for cleaning up!
Python Certification Training www.edureka.co/python
The finally Clause
finally is used for cleaning up!
try:
linux_interaction()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print('Cleaning up, irrespective of any exceptions.')
Function can only run on Linux systems.
Cleaning up, irrespective of any exceptions.
Python Certification Training www.edureka.co/python
Summary
Exception Handling In Python
Python Certification Training www.edureka.co/python
Summary
In this session, we covered the following topics:
• raise allows you to throw an exception at any time.
• assert enables you to verify if a certain condition is met and throw an
exception if it isn’t.
• In the try clause, all statements are executed until an exception is
encountered.
• except is used to catch and handle the exception(s) that are encountered in
the try clause.
• else lets you code sections that should run only when no exceptions are
encountered in the try clause.
• finally enables you to execute sections of code that should always run, with
or without any previously encountered exceptions.
Python Certification Training www.edureka.co/python
Summary
Python Programming, yay!
Exception Handling In Python | Exceptions In Python | Python Programming Tutorial | Edureka

More Related Content

What's hot (20)

Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
baabtra.com - No. 1 supplier of quality freshers
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 
Python libraries
Python librariesPython libraries
Python libraries
Prof. Dr. K. Adisesha
 
Python Generators
Python GeneratorsPython Generators
Python Generators
Akshar Raaj
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Kamal Acharya
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Srinivas Narasegouda
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Saravanan T.M
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
AbhayDhupar
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 
Python Generators
Python GeneratorsPython Generators
Python Generators
Akshar Raaj
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Srinivas Narasegouda
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 

Similar to Exception Handling In Python | Exceptions In Python | Python Programming Tutorial | Edureka (20)

Exception Handling in python programming.pptx
Exception Handling in python programming.pptxException Handling in python programming.pptx
Exception Handling in python programming.pptx
shririshsri
 
Python_Exception_Handling_Presentation.pptx
Python_Exception_Handling_Presentation.pptxPython_Exception_Handling_Presentation.pptx
Python_Exception_Handling_Presentation.pptx
csanilram
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
Pavan326406
 
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
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
Exception Handling
Exception HandlingException Handling
Exception Handling
baabtra.com - No. 1 supplier of quality freshers
 
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
 
lecs101.pdfgggggggggggggggggggddddddddddddb
lecs101.pdfgggggggggggggggggggddddddddddddblecs101.pdfgggggggggggggggggggddddddddddddb
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
Python Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and AssertionsPython Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and Assertions
Ranel Padon
 
Python Exceptions Powerpoint Presentation
Python Exceptions Powerpoint PresentationPython Exceptions Powerpoint Presentation
Python Exceptions Powerpoint Presentation
mitchellblack733
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
wulanpermatasari27
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
gandra jeeshitha
 
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
baabtra.com - No. 1 supplier of quality freshers
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
Lifna C.S
 
Exception Handling in Python Programming.pptx
Exception Handling in Python Programming.pptxException Handling in Python Programming.pptx
Exception Handling in Python Programming.pptx
vinayagrawal71
 
exception handling.pptx
exception handling.pptxexception handling.pptx
exception handling.pptx
AbinayaC11
 
Exception Handling in python programming.pptx
Exception Handling in python programming.pptxException Handling in python programming.pptx
Exception Handling in python programming.pptx
shririshsri
 
Python_Exception_Handling_Presentation.pptx
Python_Exception_Handling_Presentation.pptxPython_Exception_Handling_Presentation.pptx
Python_Exception_Handling_Presentation.pptx
csanilram
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
Pavan326406
 
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
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
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
 
lecs101.pdfgggggggggggggggggggddddddddddddb
lecs101.pdfgggggggggggggggggggddddddddddddblecs101.pdfgggggggggggggggggggddddddddddddb
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
Python Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and AssertionsPython Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and Assertions
Ranel Padon
 
Python Exceptions Powerpoint Presentation
Python Exceptions Powerpoint PresentationPython Exceptions Powerpoint Presentation
Python Exceptions Powerpoint Presentation
mitchellblack733
 
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 in python
Exception handling in pythonException handling in python
Exception handling in python
Lifna C.S
 
Exception Handling in Python Programming.pptx
Exception Handling in Python Programming.pptxException Handling in Python Programming.pptx
Exception Handling in Python Programming.pptx
vinayagrawal71
 
exception handling.pptx
exception handling.pptxexception handling.pptx
exception handling.pptx
AbinayaC11
 
Ad

More from Edureka! (20)

What to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | EdurekaWhat to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | Edureka
Edureka!
 
Top 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaTop 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | Edureka
Edureka!
 
Top 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | EdurekaTop 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | Edureka
Edureka!
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | Edureka
Edureka!
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | Edureka
Edureka!
 
Top Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | EdurekaTop Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | Edureka
Edureka!
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | Edureka
Edureka!
 
How to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaHow to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| Edureka
Edureka!
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | Edureka
Edureka!
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | Edureka
Edureka!
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | Edureka
Edureka!
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | Edureka
Edureka!
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | Edureka
Edureka!
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
Edureka!
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | Edureka
Edureka!
 
Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka
Edureka!
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaA star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
Edureka!
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | Edureka
Edureka!
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
Edureka!
 
ITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
ITIL® Tutorial for Beginners | ITIL® Foundation Training | EdurekaITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
ITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
Edureka!
 
What to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | EdurekaWhat to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | Edureka
Edureka!
 
Top 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaTop 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | Edureka
Edureka!
 
Top 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | EdurekaTop 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | Edureka
Edureka!
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | Edureka
Edureka!
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | Edureka
Edureka!
 
Top Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | EdurekaTop Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | Edureka
Edureka!
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | Edureka
Edureka!
 
How to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaHow to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| Edureka
Edureka!
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | Edureka
Edureka!
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | Edureka
Edureka!
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | Edureka
Edureka!
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | Edureka
Edureka!
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | Edureka
Edureka!
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
Edureka!
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | Edureka
Edureka!
 
Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka
Edureka!
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaA star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
Edureka!
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | Edureka
Edureka!
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
Edureka!
 
ITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
ITIL® Tutorial for Beginners | ITIL® Foundation Training | EdurekaITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
ITIL® Tutorial for Beginners | ITIL® Foundation Training | Edureka
Edureka!
 
Ad

Recently uploaded (20)

MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
GIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of UtilitiesGIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of Utilities
Safe Software
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
GIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of UtilitiesGIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of Utilities
Safe Software
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 

Exception Handling In Python | Exceptions In Python | Python Programming Tutorial | Edureka

  • 1. Python Certification Training www.edureka.co/python
  • 2. Python Certification Training www.edureka.co/python Agenda Exception Handling In Python
  • 3. Python Certification Training www.edureka.co/python Agenda Introduction 01 Why need Exception Handling? Getting Started 02 Concepts 03 Practical Approach 04 What are exceptions? Looking at code to understand theory Process of Exception Handling
  • 4. Python Certification Training www.edureka.co/python Why Need Exception Handling? Exception Handling In Python
  • 5. Python Certification Training www.edureka.co/python Why Need Exception Handling? Dividing by zero Kid Programmer
  • 6. Python Certification Training www.edureka.co/python Why Need Exception Handling? Dividing by zero Beautiful Error Message! Traceback (most recent call last): File, line 1, in <module> ZeroDivisionError: integer division or modulo by zero
  • 7. Python Certification Training www.edureka.co/python What Is Exception Handling? Exception Handling In Python
  • 8. Python Certification Training www.edureka.co/python What Is Exception Handling? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions Definition of Exception Process of responding to the occurrence, during computation, of exceptional conditions requiring special processing – often changing the normal flow of program execution Exception Handling What is an exception? What is exception handling? Let us begin!
  • 9. Python Certification Training www.edureka.co/python Process of Exception Handling Exception Handling In Python
  • 10. Python Certification Training www.edureka.co/python Process of Exception Handling Everything is fixable!How? Handle the Exception User Finds Anomaly Python Finds Anomaly User Made Mistake Fixable? Yes No Find Error Take Caution Fix Error “Catch” “Try” If you can’t, Python will! I love Python!
  • 11. Python Certification Training www.edureka.co/python Process of Exception Handling Important Terms Keyword used to keep the code segment under checktry Segment to handle the exception after catching itexcept Run this when no exceptions existelse No matter what run this code if/if not for exceptionfinally
  • 12. Python Certification Training www.edureka.co/python Process of Exception Handling Visually it looks like this!
  • 13. Python Certification Training www.edureka.co/python Coding In Python Exception Handling In Python
  • 14. Python Certification Training www.edureka.co/python Coding In Python Python code for Exception Handling >>> print( 0 / 0 )) File "<stdin>", line 1 print( 0 / 0 )) ^ SyntaxError: invalid syntax Syntax Error >>> print( 0 / 0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero Exception
  • 15. Python Certification Training www.edureka.co/python Raising An Exception We can use raise to throw an exception if a condition occurs x = 10 if x > 5: raise Exception('x should not exceed 5. The value of x was: {}'.format(x)) Traceback (most recent call last): File "<input>", line 4, in <module> Exception: x should not exceed 5. The value of x was: 10
  • 16. Python Certification Training www.edureka.co/python AssertionError Exception Instead of waiting for a program to crash midway, you can also start by making an assertion in Python import sys assert ('linux' in sys.platform), "This code runs on Linux only." Traceback (most recent call last): File "<input>", line 2, in <module> AssertionError: This code runs on Linux only.
  • 17. Python Certification Training www.edureka.co/python Try and Except Block Exception Handling In Python
  • 18. Python Certification Training www.edureka.co/python Try And Except Block The try and except block in Python is used to catch and handle exceptions def linux_interaction(): assert ('linux' in sys.platform), "Function can only run on Linux systems." print('Doing something.') try: linux_interaction() except: pass Try it out!
  • 19. Python Certification Training www.edureka.co/python Try And Except Block The program did not crash! try: linux_interaction() except: print('Linux function was not executed') Linux function was not executed
  • 20. Python Certification Training www.edureka.co/python Function can only run on Linux systems. The linux_interaction() function was not executed Try And Except Block Example where you capture the AssertionError and output message try: linux_interaction() except AssertionError as error: print(error) print('The linux_interaction() function was not executed')
  • 21. Python Certification Training www.edureka.co/python Could not open file.log Try And Except Block Another example where you open a file and use a built-in exception try: with open('file.log') as file: read_data = file.read() except: print('Could not open file.log') If file.log does not exist, this block of code will output the following:
  • 22. Python Certification Training www.edureka.co/python Exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT. Try And Except Block In the Python docs, you can see that there are a lot of built-in exceptions that you can use try: with open('file.log') as file: read_data = file.read() except FileNotFoundError as fnf_error: print(fnf_error) [Errno 2] No such file or directory: 'file.log' If file.log does not exist, this block of code will output the following:
  • 23. Python Certification Training www.edureka.co/python Try And Except Block Another Example Case try: linux_interaction() with open('file.log') as file: read_data = file.read() except FileNotFoundError as fnf_error: print(fnf_error) except AssertionError as error: print(error) print('Linux linux_interaction() function was not executed') If the file does not exist, running this code on a Windows machine will output the following: Function can only run on Linux systems. Linux linux_interaction() function was not executed [Errno 2] No such file or directory: 'file.log'
  • 24. Python Certification Training www.edureka.co/python Try And Except Block Key Takeaways • A try clause is executed up until the point where the first exception is encountered. • Inside the except clause, or the exception handler, you determine how the program responds to the exception. • You can anticipate multiple exceptions and differentiate how the program should respond to them. • Avoid using bare except clauses.
  • 25. Python Certification Training www.edureka.co/python The else Clause Exception Handling In Python
  • 26. Python Certification Training www.edureka.co/python The else Clause Using the else statement, you can instruct a program to execute a certain block of code only in the absence of exceptions
  • 27. Python Certification Training www.edureka.co/python The else Clause Example Case try: linux_interaction() except AssertionError as error: print(error) else: print('Executing the else clause.') Doing something. Executing the else clause.
  • 28. Python Certification Training www.edureka.co/python The else Clause You can also try to run code inside the else clause and catch possible exceptions there as well: try: linux_interaction() except AssertionError as error: print(error) else: try: with open('file.log') as file: read_data = file.read() except FileNotFoundError as fnf_error: print(fnf_error) Doing something. [Errno 2] No such file or directory: 'file.log'
  • 29. Python Certification Training www.edureka.co/python The finally Clause Exception Handling In Python
  • 30. Python Certification Training www.edureka.co/python The finally Clause finally is used for cleaning up!
  • 31. Python Certification Training www.edureka.co/python The finally Clause finally is used for cleaning up! try: linux_interaction() except AssertionError as error: print(error) else: try: with open('file.log') as file: read_data = file.read() except FileNotFoundError as fnf_error: print(fnf_error) finally: print('Cleaning up, irrespective of any exceptions.') Function can only run on Linux systems. Cleaning up, irrespective of any exceptions.
  • 32. Python Certification Training www.edureka.co/python Summary Exception Handling In Python
  • 33. Python Certification Training www.edureka.co/python Summary In this session, we covered the following topics: • raise allows you to throw an exception at any time. • assert enables you to verify if a certain condition is met and throw an exception if it isn’t. • In the try clause, all statements are executed until an exception is encountered. • except is used to catch and handle the exception(s) that are encountered in the try clause. • else lets you code sections that should run only when no exceptions are encountered in the try clause. • finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.
  • 34. Python Certification Training www.edureka.co/python Summary Python Programming, yay!