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
Python exception handling
PPTX
Python Exception Handling
PDF
Projection of Planes- Engineering Graphics
PPTX
USER DEFINE FUNCTIONS IN PYTHON
PPT
Introduction to problem solving in c++
PDF
VTU_Tools of Design Thinking.pdf
PPTX
Python OOPs
PPTX
Intellectual Property Rights
Python exception handling
Python Exception Handling
Projection of Planes- Engineering Graphics
USER DEFINE FUNCTIONS IN PYTHON
Introduction to problem solving in c++
VTU_Tools of Design Thinking.pdf
Python OOPs
Intellectual Property Rights

What's hot (20)

PDF
Python recursion
ODP
Python Modules
PDF
Object oriented approach in python programming
PPTX
Class, object and inheritance in python
PDF
Python File Handling | File Operations in Python | Learn python programming |...
PPTX
Object oriented programming in python
PDF
Datatypes in python
PPTX
Basics of Object Oriented Programming in Python
PPTX
Regular expressions in Python
PPTX
Chapter 03 python libraries
PPTX
Loops in Python
PDF
Variables & Data Types In Python | Edureka
PPT
Exception handling and function in python
PPTX
Generators In Python
PPTX
Exception handling
PPTX
Functions in Python
PPTX
Python Libraries and Modules
PPTX
Python-Functions.pptx
Python recursion
Python Modules
Object oriented approach in python programming
Class, object and inheritance in python
Python File Handling | File Operations in Python | Learn python programming |...
Object oriented programming in python
Datatypes in python
Basics of Object Oriented Programming in Python
Regular expressions in Python
Chapter 03 python libraries
Loops in Python
Variables & Data Types In Python | Edureka
Exception handling and function in python
Generators In Python
Exception handling
Functions in Python
Python Libraries and Modules
Python-Functions.pptx
Ad

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

PPTX
Python Lecture 7
PPTX
Error and exception in python
PPTX
Exception handling with python class 12.pptx
PPT
Py-Slides-9.ppt
PPT
PPTX
Exception handling.pptxnn h
PDF
Python programming : Exceptions
PPT
Exception Handling on 22nd March 2022.ppt
PPT
Exception Handling using Python Libraries
PPT
Exception handling in python and how to handle it
PDF
Exception-Handling Exception-HandlingFpptx.pdf
PDF
Exception-Handling Exception-HandlingFpptx.pdf
PPTX
Python Session - 6
PPT
Exception handling
PPTX
EXCEPTION HANDLING IN PYTHON For students .py.pptx
PPT
04_1.Exceptionssssssssssssssssssss..pptt
PPTX
presentation-on-exception-handling 1.pptx
PPTX
presentation-on-exception-handling-160611180456 (1).pptx
PPT
Exception Handling.ppt
PPTX
Python Programming Essentials - M21 - Exception Handling
Python Lecture 7
Error and exception in python
Exception handling with python class 12.pptx
Py-Slides-9.ppt
Exception handling.pptxnn h
Python programming : Exceptions
Exception Handling on 22nd March 2022.ppt
Exception Handling using Python Libraries
Exception handling in python and how to handle it
Exception-Handling Exception-HandlingFpptx.pdf
Exception-Handling Exception-HandlingFpptx.pdf
Python Session - 6
Exception handling
EXCEPTION HANDLING IN PYTHON For students .py.pptx
04_1.Exceptionssssssssssssssssssss..pptt
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling-160611180456 (1).pptx
Exception Handling.ppt
Python Programming Essentials - M21 - Exception Handling
Ad

More from Edureka! (20)

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

Recently uploaded (20)

PPTX
Blending method and technology for hydrogen.pptx
PPTX
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
PDF
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
PDF
Secure Java Applications against Quantum Threats
PDF
Ebook - The Future of AI A Comprehensive Guide.pdf
PDF
Examining Bias in AI Generated News Content.pdf
PDF
TicketRoot: Event Tech Solutions Deck 2025
PDF
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
PDF
Introduction to c language from lecture slides
PDF
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
PPTX
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
PPTX
How to use fields_get method in Odoo 18
PDF
The AI Revolution in Customer Service - 2025
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
Optimizing bioinformatics applications: a novel approach with human protein d...
PPTX
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
PPTX
Information-Technology-in-Human-Society.pptx
PDF
Addressing the challenges of harmonizing law and artificial intelligence tech...
PPTX
From XAI to XEE through Influence and Provenance.Controlling model fairness o...
PDF
substrate PowerPoint Presentation basic one
Blending method and technology for hydrogen.pptx
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
Secure Java Applications against Quantum Threats
Ebook - The Future of AI A Comprehensive Guide.pdf
Examining Bias in AI Generated News Content.pdf
TicketRoot: Event Tech Solutions Deck 2025
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
Introduction to c language from lecture slides
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
How to use fields_get method in Odoo 18
The AI Revolution in Customer Service - 2025
Presentation - Principles of Instructional Design.pptx
Optimizing bioinformatics applications: a novel approach with human protein d...
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
Information-Technology-in-Human-Society.pptx
Addressing the challenges of harmonizing law and artificial intelligence tech...
From XAI to XEE through Influence and Provenance.Controlling model fairness o...
substrate PowerPoint Presentation basic one

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!