SlideShare a Scribd company logo
http://www.skillbrew.com
/Skillbrew
Talent brewed by the industry itself
Exception Handling in python
Pavan Verma
@YinYangPavan
Founder, P3 InfoTech Solutions Pvt. Ltd.
1
Python Programming Essentials
© SkillBrew http://skillbrew.com
Contents
 Exceptions
 Throwing and catching exceptions
 try except
 try except else
 try except finally
 Common python exceptions
2
© SkillBrew http://skillbrew.com
What is an Exception?
 An exception is an error that happens
during execution of a program
 If an exception is not caught the program
is terminated
 In Python, exceptions are triggered
automatically on errors, and they can be
triggered and intercepted by your code
3
© SkillBrew http://skillbrew.com
Exceptions
 Exception handling has two steps:
• Raising or Throwing
• Catching
 Python provides 3 keywords to deal with
exceptions :
• raise
• try
• except
4
© SkillBrew http://skillbrew.com
Exceptions (2)
Program to divide a constant by a number
def divide(num):
print 100/num
if __name__ == '__main__':
divide(0)
OUPUT:
ZeroDivisionError: integer division or modulo by zero
5
© SkillBrew http://skillbrew.com
Exception propagation
6
>>> f1(0)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in
<module>
f1(0)
File "<pyshell#8>", line 2, in f1
return f2(num)
File "<pyshell#5>", line 2, in f2
return f3(num)
File "<pyshell#2>", line 3, in f3
return constant/num
ZeroDivisionError: integer division
or modulo by zero
>>> def f3(num):
constant = 100
return constant/num
>>> def f2(num):
return f3(num)
>>> def f1(num):
return f2(num)
>>> f1(10)
10
>>> f1(0)
© SkillBrew http://skillbrew.com
Why use exceptions
 Error handling: Python raises an exception whenever
it detects errors in program at runtime. You can catch
and respond to errors in the code or Python’s default
behavior kicks in, stops the program and prints the
error message.
 Event notification: exceptions can also be used to
signal valid conditions without you having to pass
result flags around a program
7
© SkillBrew http://skillbrew.com
Throwing and Catching Exceptions
8
© SkillBrew http://skillbrew.com
Throwing an exception
9
def avg(seq):
result = 0
for val in seq:
result += convert(val)
return result/len(seq)
def convert(val):
try:
val = int(val)
except ValueError:
raise ValueError('val type is not int')
return val
print avg([1, 2, 4, 5])
Output:
3
© SkillBrew http://skillbrew.com
Throwing an exception
10
print avg([1, 'two', 4, 5])
Output:
Traceback (most recent call last):
File "exceptions1.py", line 15, in <module>
print avg([1, 'two', 4, 5])
File "exceptions1.py", line 4, in avg
result += convert(val)
File "exceptions1.py", line 11, in convert
raise ValueError('val type is not int')
ValueError: val type is not int
© SkillBrew http://skillbrew.com
Handling Exceptions (try except block)
 In order to handle exceptions wrap the code in try
except
def divide(num):
try:
print 100/num
except ZeroDivisionError:
print("division by Zero not allowed")
if __name__=='__main__':
divide(0)
Output:
division by Zero not allowed
11
© SkillBrew http://skillbrew.com
try except else
12
try:
# do something
except:
# handle exception
else:
# executed only when there is no exception
The code in else block is only executed if there is no
exception
© SkillBrew http://skillbrew.com
try except else (2)
def divide(num):
try:
result = 100/num
except ZeroDivisionError:
print('division by Zero not allowed')
else:
print “Result is %d" % (result)
if __name__ == '__main__':
divide(10)
Output:
Result is 10
13
© SkillBrew http://skillbrew.com
try except finally
14
try:
# do something
except:
# handle exception
finally:
# always executed
The code in finally block is always executed, no
matter what
© SkillBrew http://skillbrew.com
try except finally (2)
15
def divide(num):
try:
result = 100/num
except ZeroDivisionError:
print('division by Zero not allowed')
finally:
print “Input was %d" % (num)
if __name__ == '__main__':
divide(0)
Output:
Division by Zero not allowed
Your input was 0
© SkillBrew http://skillbrew.com
Common Python Exceptions
Exception Description
IOError If the file cannot be opened
ImportError If python cannot find the module
ValueError Raised when a built-in operation or
function receives an argument that has
the right type but an inappropriate value
KeyError Raised when a mapping (dictionary) key is
not found in the set of existing keys
IndentationError raised due to incorrect indentation
SyntaxError Raised when the parser encounters a
syntax error
16
© SkillBrew http://skillbrew.com
Custom exceptions
class MyException(Exception):
pass
def divide(num):
try:
return 100/num
except ZeroDivisionError:
raise MyException('Cannot divide
by 0')
17
© SkillBrew http://skillbrew.com
Resources
 http://doughellmann.com/2009/06/pyth
on-exception-handling-techniques.html
18

More Related Content

PPTX
Class, object and inheritance in python
Santosh Verma
 
PPTX
Object oriented programming with python
Arslan Arshad
 
PPTX
Selection sorting
Himanshu Kesharwani
 
PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PDF
Set methods in python
deepalishinkar1
 
PPTX
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
PPT
C++ Arrays
أحمد محمد
 
Class, object and inheritance in python
Santosh Verma
 
Object oriented programming with python
Arslan Arshad
 
Selection sorting
Himanshu Kesharwani
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Set methods in python
deepalishinkar1
 
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
C++ Arrays
أحمد محمد
 

What's hot (20)

PPT
Class and Objects in PHP
Ramasubbu .P
 
PDF
04. constructor & destructor
Haresh Jaiswal
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PDF
Object oriented approach in python programming
Srinivas Narasegouda
 
PPTX
Sum of subset problem.pptx
V.V.Vanniaperumal College for Women
 
PPTX
Access specifiers(modifiers) in java
HrithikShinde
 
PPTX
Classification of datastructure.ppt
LakshmiSamivel
 
PPTX
Chapter 07 inheritance
Praveen M Jigajinni
 
PPT
Basic concepts of object oriented programming
Sachin Sharma
 
PDF
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Edureka!
 
PDF
Operator overloading
Pranali Chaudhari
 
PPTX
Virtual Functions | Polymorphism | OOP
shubham ghimire
 
PPTX
Presentation on the topic selection sort
District Administration
 
PPTX
Insertion sort algorithm power point presentation
University of Science and Technology Chitttagong
 
PPTX
Storage classes in c++
Jaspal Singh
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
PPTX
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
PDF
What is Python JSON | Edureka
Edureka!
 
PPTX
Advanced Python : Decorators
Bhanwar Singh Meena
 
Class and Objects in PHP
Ramasubbu .P
 
04. constructor & destructor
Haresh Jaiswal
 
Python: Modules and Packages
Damian T. Gordon
 
Object oriented approach in python programming
Srinivas Narasegouda
 
Sum of subset problem.pptx
V.V.Vanniaperumal College for Women
 
Access specifiers(modifiers) in java
HrithikShinde
 
Classification of datastructure.ppt
LakshmiSamivel
 
Chapter 07 inheritance
Praveen M Jigajinni
 
Basic concepts of object oriented programming
Sachin Sharma
 
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Edureka!
 
Operator overloading
Pranali Chaudhari
 
Virtual Functions | Polymorphism | OOP
shubham ghimire
 
Presentation on the topic selection sort
District Administration
 
Insertion sort algorithm power point presentation
University of Science and Technology Chitttagong
 
Storage classes in c++
Jaspal Singh
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
What is Python JSON | Edureka
Edureka!
 
Advanced Python : Decorators
Bhanwar Singh Meena
 
Ad

Viewers also liked (14)

ODP
Exception handling in python
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Libraries
Marieswaran Ramasamy
 
PPTX
Python Programming Essentials - M4 - Editors and IDEs
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M9 - String Formatting
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M23 - datetime module
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M1 - Course Introduction
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M7 - Strings
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M40 - Invoking External Programs
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M28 - Debugging with pdb
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M31 - PEP 8
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M44 - Overview of Web Development
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Python Programming Essentials - M4 - Editors and IDEs
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M9 - String Formatting
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M23 - datetime module
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M1 - Course Introduction
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M7 - Strings
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M40 - Invoking External Programs
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M28 - Debugging with pdb
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M31 - PEP 8
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M44 - Overview of Web Development
P3 InfoTech Solutions Pvt. Ltd.
 
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Ad

Similar to Python Programming Essentials - M21 - Exception Handling (20)

PPTX
Exception Handling in python programming.pptx
shririshsri
 
PDF
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
PPTX
Exception handling.pptxnn h
sabarivelan111007
 
PPTX
Python Lecture 7
Inzamam Baig
 
PPTX
Exception Handling in Python Programming.pptx
vinayagrawal71
 
PPTX
Exception Handling in Python programming.pptx
vinayagrawal71
 
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
PDF
Exception handling in python
Lifna C.S
 
PPTX
Exception Handling in Python
DrJasmineBeulahG
 
PPTX
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
PDF
Unit 4-Exception Handling in Python.pdf
Harsha Patil
 
PPT
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
PPTX
Python_Exception_Handling_Presentation.pptx
csanilram
 
PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
PPTX
Download Wondershare Filmora Crack Latest 2025
hyderik195
 
PPTX
Adobe Photoshop 2025 Cracked Latest Version
hyderik195
 
PPTX
FL Studio Producer Edition Crack 24 + Latest Version [2025]
hyderik195
 
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Exception Handling in python programming.pptx
shririshsri
 
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
Exception handling.pptxnn h
sabarivelan111007
 
Python Lecture 7
Inzamam Baig
 
Exception Handling in Python Programming.pptx
vinayagrawal71
 
Exception Handling in Python programming.pptx
vinayagrawal71
 
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
Exception handling in python
Lifna C.S
 
Exception Handling in Python
DrJasmineBeulahG
 
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
Unit 4-Exception Handling in Python.pdf
Harsha Patil
 
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
Python_Exception_Handling_Presentation.pptx
csanilram
 
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
Download Wondershare Filmora Crack Latest 2025
hyderik195
 
Adobe Photoshop 2025 Cracked Latest Version
hyderik195
 
FL Studio Producer Edition Crack 24 + Latest Version [2025]
hyderik195
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 

More from P3 InfoTech Solutions Pvt. Ltd. (20)

PPTX
Python Programming Essentials - M39 - Unit Testing
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M35 - Iterators & Generators
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M34 - List Comprehensions
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M29 - Python Interpreter and Files
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M27 - Logging module
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M24 - math module
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M22 - File Operations
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M20 - Classes and Objects
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M18 - Modules and Packages
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M17 - Functions
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M16 - Control Flow Statements and Loops
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M15 - References
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M14 - Dictionaries
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M13 - Tuples
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M12 - Lists
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M11 - Comparison and Logical Operators
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python Programming Essentials - M6 - Code Blocks and Indentation
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M39 - Unit Testing
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M35 - Iterators & Generators
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M34 - List Comprehensions
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M29 - Python Interpreter and Files
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M27 - Logging module
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M24 - math module
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M22 - File Operations
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M20 - Classes and Objects
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M18 - Modules and Packages
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M17 - Functions
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M15 - References
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M14 - Dictionaries
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M13 - Tuples
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M12 - Lists
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M11 - Comparison and Logical Operators
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M6 - Code Blocks and Indentation
P3 InfoTech Solutions Pvt. Ltd.
 

Python Programming Essentials - M21 - Exception Handling