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

What's hot

Exception handling in python
Exception handling in pythonException handling in python
Exception handling in pythonLifna C.S
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in cMemo Yekem
 
Python Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and AssertionsPython Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and AssertionsRanel Padon
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsPython Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsP3 InfoTech Solutions Pvt. Ltd.
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling sharqiyem
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cppgourav kottawar
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .NetMindfire Solutions
 
Exception handler
Exception handler Exception handler
Exception handler dishni
 

What's hot (20)

Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
 
Python Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and AssertionsPython Programming - X. Exception Handling and Assertions
Python Programming - X. Exception Handling and Assertions
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsPython Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
 
Exception handling
Exception handlingException handling
Exception handling
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Exception handling
Exception handlingException handling
Exception handling
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
Rc2010 tdd
Rc2010 tddRc2010 tdd
Rc2010 tdd
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling
Exception handlingException handling
Exception handling
 
C++ ala
C++ alaC++ ala
C++ ala
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
 
Exception handler
Exception handler Exception handler
Exception handler
 

Viewers also liked

Python Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M10 - Numbers and Artihmetic OperatorsPython Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M10 - Numbers and Artihmetic OperatorsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M1 - Course Introduction
Python Programming Essentials - M1 - Course IntroductionPython Programming Essentials - M1 - Course Introduction
Python Programming Essentials - M1 - Course IntroductionP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentP3 InfoTech Solutions Pvt. Ltd.
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 

Viewers also liked (14)

Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Libraries
LibrariesLibraries
Libraries
 
Python Programming Essentials - M4 - Editors and IDEs
Python Programming Essentials - M4 - Editors and IDEsPython Programming Essentials - M4 - Editors and IDEs
Python Programming Essentials - M4 - Editors and IDEs
 
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M10 - Numbers and Artihmetic OperatorsPython Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
 
Python Programming Essentials - M1 - Course Introduction
Python Programming Essentials - M1 - Course IntroductionPython Programming Essentials - M1 - Course Introduction
Python Programming Essentials - M1 - Course Introduction
 
Python Programming Essentials - M7 - Strings
Python Programming Essentials - M7 - StringsPython Programming Essentials - M7 - Strings
Python Programming Essentials - M7 - Strings
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External Programs
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdb
 
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8
 
Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web Development
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 

Similar to Python Programming Essentials - M21 - Exception Handling

Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.pptSanthiNivas
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16Max Kleiner
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]ppd1961
 
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱Mohammad Reza Kamalifard
 
Exception handling
Exception handlingException handling
Exception handlingWaqas Abbasi
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Exception Handling
Exception HandlingException Handling
Exception HandlingAlpesh Oza
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 

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

Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
43c
43c43c
43c
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Unit iii pds
Unit iii pdsUnit iii pds
Unit iii pds
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 

More from P3 InfoTech Solutions Pvt. Ltd.

Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsPython Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationP3 InfoTech Solutions Pvt. Ltd.
 

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

Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List Comprehensions
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and Files
 
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging modulePython Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging module
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
 
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File OperationsPython Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File Operations
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and Packages
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python Programming Essentials - M15 - References
Python Programming Essentials - M15 - ReferencesPython Programming Essentials - M15 - References
Python Programming Essentials - M15 - References
 
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - DictionariesPython Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - Dictionaries
 
Python Programming Essentials - M13 - Tuples
Python Programming Essentials - M13 - TuplesPython Programming Essentials - M13 - Tuples
Python Programming Essentials - M13 - Tuples
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
 
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsPython Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical Operators
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and Indentation
 
Python Programming Essentials - M5 - Variables
Python Programming Essentials - M5 - VariablesPython Programming Essentials - M5 - Variables
Python Programming Essentials - M5 - Variables
 

Python Programming Essentials - M21 - Exception Handling

  • 1. 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
  • 2. © SkillBrew http://skillbrew.com Contents  Exceptions  Throwing and catching exceptions  try except  try except else  try except finally  Common python exceptions 2
  • 3. © 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
  • 4. © 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
  • 5. © 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
  • 6. © 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)
  • 7. © 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
  • 8. © SkillBrew http://skillbrew.com Throwing and Catching Exceptions 8
  • 9. © 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
  • 10. © 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
  • 11. © 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
  • 12. © 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
  • 13. © 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
  • 14. © 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
  • 15. © 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
  • 16. © 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
  • 17. © 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
  • 18. © SkillBrew http://skillbrew.com Resources  http://doughellmann.com/2009/06/pyth on-exception-handling-techniques.html 18