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

PDF
Strings in python
Prabhakaran V M
 
PDF
Data Science Full Course | Edureka
Edureka!
 
PDF
Projection of Planes- Engineering Graphics
Dr Ramesh B T
 
PDF
Linear Algebra – A Powerful Tool for Data Science
Premier Publishers
 
PDF
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Edureka!
 
PPT
Engineering drawing chapter 03 orthographic projection.
Talha Mughal
 
PDF
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Edureka!
 
PPTX
Development of surfaces
sushma chinta
 
Strings in python
Prabhakaran V M
 
Data Science Full Course | Edureka
Edureka!
 
Projection of Planes- Engineering Graphics
Dr Ramesh B T
 
Linear Algebra – A Powerful Tool for Data Science
Premier Publishers
 
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Edureka!
 
Engineering drawing chapter 03 orthographic projection.
Talha Mughal
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Edureka!
 
Development of surfaces
sushma chinta
 

What's hot (20)

PPTX
Exception handling
PhD Research Scholar
 
PPTX
Python Functions
Mohammed Sikander
 
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
PPT
Exception handling
Tata Consultancy Services
 
PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PPTX
Python Exception Handling
Megha V
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PPTX
Python OOPs
Binay Kumar Ray
 
ODP
Python Modules
Nitin Reddy Katkam
 
PDF
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
PPTX
Error and exception in python
junnubabu
 
PPTX
Regular expressions in Python
Sujith Kumar
 
PPTX
Basics of Object Oriented Programming in Python
Sujith Kumar
 
PPTX
OOP concepts -in-Python programming language
SmritiSharma901052
 
PPTX
File handling in Python
Megha V
 
PDF
Java exception handling ppt
JavabynataraJ
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
PPTX
Strings in Java
Abhilash Nair
 
PDF
Object oriented approach in python programming
Srinivas Narasegouda
 
PDF
Serialization & De-serialization in Java
InnovationM
 
Exception handling
PhD Research Scholar
 
Python Functions
Mohammed Sikander
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Exception handling
Tata Consultancy Services
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Python Exception Handling
Megha V
 
Modules and packages in python
TMARAGATHAM
 
Python OOPs
Binay Kumar Ray
 
Python Modules
Nitin Reddy Katkam
 
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
Error and exception in python
junnubabu
 
Regular expressions in Python
Sujith Kumar
 
Basics of Object Oriented Programming in Python
Sujith Kumar
 
OOP concepts -in-Python programming language
SmritiSharma901052
 
File handling in Python
Megha V
 
Java exception handling ppt
JavabynataraJ
 
Python functions
Prof. Dr. K. Adisesha
 
Strings in Java
Abhilash Nair
 
Object oriented approach in python programming
Srinivas Narasegouda
 
Serialization & De-serialization in Java
InnovationM
 
Ad

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

PPTX
Python Lecture 7
Inzamam Baig
 
PPTX
Exception handling with python class 12.pptx
PreeTVithule1
 
PPT
Py-Slides-9.ppt
wulanpermatasari27
 
PPT
Exception
Navaneethan Naveen
 
PPTX
Exception handling.pptxnn h
sabarivelan111007
 
PPT
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
PPT
Exception Handling using Python Libraries
mmvrm
 
PPT
Exception handling in python and how to handle it
s6901412
 
PDF
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
PDF
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
PPTX
Python Session - 6
AnirudhaGaikwad4
 
PPT
Exception handling
Sandeep Rawat
 
PPTX
EXCEPTION HANDLING IN PYTHON For students .py.pptx
MihirBhardwaj3
 
PPT
04_1.Exceptionssssssssssssssssssss..pptt
NguynQunhTrang55
 
PPTX
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
PPTX
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
PPT
Exception Handling.ppt
Faisaliqbal203156
 
PPTX
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Unit II.pptx
sarthakgithub
 
PDF
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
Mohammad Reza Kamalifard
 
Python Lecture 7
Inzamam Baig
 
Exception handling with python class 12.pptx
PreeTVithule1
 
Py-Slides-9.ppt
wulanpermatasari27
 
Exception handling.pptxnn h
sabarivelan111007
 
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
Exception Handling using Python Libraries
mmvrm
 
Exception handling in python and how to handle it
s6901412
 
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
Exception-Handling Exception-HandlingFpptx.pdf
jeevithequeen2025
 
Python Session - 6
AnirudhaGaikwad4
 
Exception handling
Sandeep Rawat
 
EXCEPTION HANDLING IN PYTHON For students .py.pptx
MihirBhardwaj3
 
04_1.Exceptionssssssssssssssssssss..pptt
NguynQunhTrang55
 
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
Exception Handling.ppt
Faisaliqbal203156
 
Python Programming Essentials - M21 - Exception Handling
P3 InfoTech Solutions Pvt. Ltd.
 
Python Unit II.pptx
sarthakgithub
 
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
Mohammad Reza Kamalifard
 
Ad

More from Edureka! (20)

PDF
What to learn during the 21 days Lockdown | Edureka
Edureka!
 
PDF
Top 10 Dying Programming Languages in 2020 | Edureka
Edureka!
 
PDF
Top 5 Trending Business Intelligence Tools | Edureka
Edureka!
 
PDF
Tableau Tutorial for Data Science | Edureka
Edureka!
 
PDF
Python Programming Tutorial | Edureka
Edureka!
 
PDF
Top 5 PMP Certifications | Edureka
Edureka!
 
PDF
Top Maven Interview Questions in 2020 | Edureka
Edureka!
 
PDF
Linux Mint Tutorial | Edureka
Edureka!
 
PDF
How to Deploy Java Web App in AWS| Edureka
Edureka!
 
PDF
Importance of Digital Marketing | Edureka
Edureka!
 
PDF
RPA in 2020 | Edureka
Edureka!
 
PDF
Email Notifications in Jenkins | Edureka
Edureka!
 
PDF
EA Algorithm in Machine Learning | Edureka
Edureka!
 
PDF
Cognitive AI Tutorial | Edureka
Edureka!
 
PDF
AWS Cloud Practitioner Tutorial | Edureka
Edureka!
 
PDF
Blue Prism Top Interview Questions | Edureka
Edureka!
 
PDF
Big Data on AWS Tutorial | Edureka
Edureka!
 
PDF
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
Edureka!
 
PDF
Kubernetes Installation on Ubuntu | Edureka
Edureka!
 
PDF
Introduction to DevOps | Edureka
Edureka!
 
What to learn during the 21 days Lockdown | Edureka
Edureka!
 
Top 10 Dying Programming Languages in 2020 | Edureka
Edureka!
 
Top 5 Trending Business Intelligence Tools | Edureka
Edureka!
 
Tableau Tutorial for Data Science | Edureka
Edureka!
 
Python Programming Tutorial | Edureka
Edureka!
 
Top 5 PMP Certifications | Edureka
Edureka!
 
Top Maven Interview Questions in 2020 | Edureka
Edureka!
 
Linux Mint Tutorial | Edureka
Edureka!
 
How to Deploy Java Web App in AWS| Edureka
Edureka!
 
Importance of Digital Marketing | Edureka
Edureka!
 
RPA in 2020 | Edureka
Edureka!
 
Email Notifications in Jenkins | Edureka
Edureka!
 
EA Algorithm in Machine Learning | Edureka
Edureka!
 
Cognitive AI Tutorial | Edureka
Edureka!
 
AWS Cloud Practitioner Tutorial | Edureka
Edureka!
 
Blue Prism Top Interview Questions | Edureka
Edureka!
 
Big Data on AWS Tutorial | Edureka
Edureka!
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
Edureka!
 
Kubernetes Installation on Ubuntu | Edureka
Edureka!
 
Introduction to DevOps | Edureka
Edureka!
 

Recently uploaded (20)

PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 

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!