** Python Certification Training: https://www.edureka.co/python-programming-certification-training **
This Edureka PPT on Exception Handling Tutorial covers all the important aspects of making use and working with Exceptions using Python. It establishes all of the concepts like explaining why we need exception handling, the process of exception handling and how to go about using it practically.
Agenda
Why need Exception Handling?
What is Exception Handling?
Process of Exception Handling
Coding with Python
Try and Except block in Python
The else clause
The finally clause
Summary
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Instagram: https://www.instagram.com/edureka_lea...
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
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
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
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!
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
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.
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.
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'
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.
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.