SlideShare a Scribd company logo
1 of 35
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

Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Python Generators
Python GeneratorsPython Generators
Python GeneratorsAkshar Raaj
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Filesprimeteacher32
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabaseElangovanTechNotesET
 
Conditionalstatement
ConditionalstatementConditionalstatement
ConditionalstatementRaginiJain21
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Edureka!
 

What's hot (20)

Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Namespaces
NamespacesNamespaces
Namespaces
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
 

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

Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
Exception Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptException Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptRaja Ram Dutta
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingP3 InfoTech Solutions Pvt. Ltd.
 
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱Mohammad Reza Kamalifard
 
Introduction To Programming with Python-5
Introduction To Programming with Python-5Introduction To Programming with Python-5
Introduction To Programming with Python-5Syed Farjad Zia Zaidi
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Edureka!
 
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!
 

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

Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
 
Exception
ExceptionException
Exception
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
 
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
 
Python Session - 6
Python Session - 6Python Session - 6
Python Session - 6
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
 
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
 
Introduction To Programming with Python-5
Introduction To Programming with Python-5Introduction To Programming with Python-5
Introduction To Programming with Python-5
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
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 |...
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 

More from 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 | EdurekaEdureka!
 
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 | EdurekaEdureka!
 
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 | EdurekaEdureka!
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaEdureka!
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaEdureka!
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaEdureka!
 
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 | EdurekaEdureka!
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaEdureka!
 
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| EdurekaEdureka!
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaEdureka!
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | EdurekaEdureka!
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEdureka!
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEdureka!
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaEdureka!
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaEdureka!
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaEdureka!
 
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 | EdurekaEdureka!
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaEdureka!
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | EdurekaEdureka!
 

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
 
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
 
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
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | Edureka
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | 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
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | 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
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | Edureka
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | Edureka
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | Edureka
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | Edureka
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | Edureka
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | 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
 
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
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | Edureka
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
 

Recently uploaded

Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 

Recently uploaded (20)

Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 

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!