Movatterモバイル変換


[0]ホーム

URL:


2,182 views

Python Programming Essentials - M21 - Exception Handling

This document discusses exception handling in Python. It explains that exceptions are errors that occur during program execution and can be handled using try, except, and raise keywords. The document covers throwing exceptions, catching exceptions using try/except blocks, propagating exceptions, using try/except/else and try/except/finally, and some common built-in Python exceptions. It also provides an example of defining a custom exception class.

Embed presentation

http://www.skillbrew.com/SkillbrewTalent brewed by the industry itselfException Handling in pythonPavan Verma@YinYangPavanFounder, P3 InfoTech Solutions Pvt. Ltd.1Python Programming Essentials
© SkillBrew http://skillbrew.comContents Exceptions Throwing and catching exceptions try except try except else try except finally Common python exceptions2
© SkillBrew http://skillbrew.comWhat is an Exception? An exception is an error that happensduring execution of a program If an exception is not caught the programis terminated In Python, exceptions are triggeredautomatically on errors, and they can betriggered and intercepted by your code3
© SkillBrew http://skillbrew.comExceptions Exception handling has two steps:• Raising or Throwing• Catching Python provides 3 keywords to deal withexceptions :• raise• try• except4
© SkillBrew http://skillbrew.comExceptions (2)Program to divide a constant by a numberdef divide(num):print 100/numif __name__ == '__main__':divide(0)OUPUT:ZeroDivisionError: integer division or modulo by zero5
© SkillBrew http://skillbrew.comException propagation6>>> f1(0)Traceback (most recent call last):File "<pyshell#10>", line 1, in<module>f1(0)File "<pyshell#8>", line 2, in f1return f2(num)File "<pyshell#5>", line 2, in f2return f3(num)File "<pyshell#2>", line 3, in f3return constant/numZeroDivisionError: integer divisionor modulo by zero>>> def f3(num):constant = 100return constant/num>>> def f2(num):return f3(num)>>> def f1(num):return f2(num)>>> f1(10)10>>> f1(0)
© SkillBrew http://skillbrew.comWhy use exceptions Error handling: Python raises an exception wheneverit detects errors in program at runtime. You can catchand respond to errors in the code or Python’s defaultbehavior kicks in, stops the program and prints theerror message. Event notification: exceptions can also be used tosignal valid conditions without you having to passresult flags around a program7
© SkillBrew http://skillbrew.comThrowing and Catching Exceptions8
© SkillBrew http://skillbrew.comThrowing an exception9def avg(seq):result = 0for 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 valprint avg([1, 2, 4, 5])Output:3
© SkillBrew http://skillbrew.comThrowing an exception10print 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 avgresult += convert(val)File "exceptions1.py", line 11, in convertraise ValueError('val type is not int')ValueError: val type is not int
© SkillBrew http://skillbrew.comHandling Exceptions (try except block) In order to handle exceptions wrap the code in tryexceptdef divide(num):try:print 100/numexcept ZeroDivisionError:print("division by Zero not allowed")if __name__=='__main__':divide(0)Output:division by Zero not allowed11
© SkillBrew http://skillbrew.comtry except else12try:# do somethingexcept:# handle exceptionelse:# executed only when there is no exceptionThe code in else block is only executed if there is noexception
© SkillBrew http://skillbrew.comtry except else (2)def divide(num):try:result = 100/numexcept ZeroDivisionError:print('division by Zero not allowed')else:print “Result is %d" % (result)if __name__ == '__main__':divide(10)Output:Result is 1013
© SkillBrew http://skillbrew.comtry except finally14try:# do somethingexcept:# handle exceptionfinally:# always executedThe code in finally block is always executed, nomatter what
© SkillBrew http://skillbrew.comtry except finally (2)15def divide(num):try:result = 100/numexcept ZeroDivisionError:print('division by Zero not allowed')finally:print “Input was %d" % (num)if __name__ == '__main__':divide(0)Output:Division by Zero not allowedYour input was 0
© SkillBrew http://skillbrew.comCommon Python ExceptionsException DescriptionIOError If the file cannot be openedImportError If python cannot find the moduleValueError Raised when a built-in operation orfunction receives an argument that hasthe right type but an inappropriate valueKeyError Raised when a mapping (dictionary) key isnot found in the set of existing keysIndentationError raised due to incorrect indentationSyntaxError Raised when the parser encounters asyntax error16
© SkillBrew http://skillbrew.comCustom exceptionsclass MyException(Exception):passdef divide(num):try:return 100/numexcept ZeroDivisionError:raise MyException('Cannot divideby 0')17
© SkillBrew http://skillbrew.comResources http://doughellmann.com/2009/06/python-exception-handling-techniques.html18

Recommended

PPTX
Python Exception Handling
ODP
Exception handling in python
PPTX
JAVA-PPT'S.pptx
PPTX
Static Data Members and Member Functions
PPTX
Python Functions
PPT
Queue data structure
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPTX
Operators in Python
PDF
Introduction to python programming
PPT
Python Control structures
PPTX
Exception Handling in Python
PPT
Basic concept of OOP's
PDF
Oops concepts || Object Oriented Programming Concepts in Java
PPSX
Break and continue
PPTX
Introduction to the basics of Python programming (part 1)
PPTX
Scope rules : local and global variables
PDF
Learn C# Programming - Decision Making & Loops
PDF
What is Serialization in Java? | Java Tutorial | Edureka
PPTX
Data Types, Variables, and Operators
PPTX
For Loops and Nesting in Python
PDF
PPTX
Java script
PPTX
Types of grammer - TOC
PPTX
Values and Data types in python
PPSX
Data Structure (Queue)
PPTX
PDF
Asymptotic Notation
PDF
07.2 Holland's Genetic Algorithms Schema Theorem
PPTX
Python Programming Essentials - M7 - Strings
PPTX
Python Programming Essentials - M31 - PEP 8

More Related Content

PPTX
Python Exception Handling
ODP
Exception handling in python
PPTX
JAVA-PPT'S.pptx
PPTX
Static Data Members and Member Functions
PPTX
Python Functions
PPT
Queue data structure
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPTX
Operators in Python
Python Exception Handling
Exception handling in python
JAVA-PPT'S.pptx
Static Data Members and Member Functions
Python Functions
Queue data structure
Basic Concepts of OOPs (Object Oriented Programming in Java)
Operators in Python

What's hot

PDF
Introduction to python programming
PPT
Python Control structures
PPTX
Exception Handling in Python
PPT
Basic concept of OOP's
PDF
Oops concepts || Object Oriented Programming Concepts in Java
PPSX
Break and continue
PPTX
Introduction to the basics of Python programming (part 1)
PPTX
Scope rules : local and global variables
PDF
Learn C# Programming - Decision Making & Loops
PDF
What is Serialization in Java? | Java Tutorial | Edureka
PPTX
Data Types, Variables, and Operators
PPTX
For Loops and Nesting in Python
PDF
PPTX
Java script
PPTX
Types of grammer - TOC
PPTX
Values and Data types in python
PPSX
Data Structure (Queue)
PPTX
PDF
Asymptotic Notation
PDF
07.2 Holland's Genetic Algorithms Schema Theorem
Introduction to python programming
Python Control structures
Exception Handling in Python
Basic concept of OOP's
Oops concepts || Object Oriented Programming Concepts in Java
Break and continue
Introduction to the basics of Python programming (part 1)
Scope rules : local and global variables
Learn C# Programming - Decision Making & Loops
What is Serialization in Java? | Java Tutorial | Edureka
Data Types, Variables, and Operators
For Loops and Nesting in Python
Java script
Types of grammer - TOC
Values and Data types in python
Data Structure (Queue)
Asymptotic Notation
07.2 Holland's Genetic Algorithms Schema Theorem

Viewers also liked

PPTX
Python Programming Essentials - M7 - Strings
PPTX
Python Programming Essentials - M31 - PEP 8
PPTX
Python Programming Essentials - M23 - datetime module
PPTX
Basics of Object Oriented Programming in Python
PPTX
Python Programming Essentials - M9 - String Formatting
PPTX
Python Programming Essentials - M8 - String Methods
PPTX
Python Programming Essentials - M4 - Editors and IDEs
PPTX
Python Programming Essentials - M40 - Invoking External Programs
PPTX
Python Programming Essentials - M1 - Course Introduction
PPTX
Python Programming Essentials - M44 - Overview of Web Development
PPTX
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
PPTX
Python Programming Essentials - M28 - Debugging with pdb
PDF
Python Programming Essentials - M7 - Strings
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M23 - datetime module
Basics of Object Oriented Programming in Python
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M4 - Editors and IDEs
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M1 - Course Introduction
Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M10 - Numbers and Artihmetic Operators
Python Programming Essentials - M28 - Debugging with pdb

Similar to Python Programming Essentials - M21 - Exception Handling

PDF
Python programming : Exceptions
PPTX
Python Exception handling using Try-Except-Finally
PPTX
Exception handling.pptxnn h
PDF
Unit 4-Exception Handling in Python.pdf
PPTX
EXCEPTION HANDLING class 12th computer science.pptx
PPTX
Exception Handling in python programming.pptx
PPTX
Exception Handling in Python programming.pptx
PPTX
Exception Handling in Python Programming.pptx
PPTX
Python_Exception_Handling_Presentation.pptx
PDF
Exception handling in python
PPT
Exception Handling on 22nd March 2022.ppt
PDF
EXCEPTION HANDLING - PYTHON COMPUTER SCIENCE
PPTX
Download Wondershare Filmora Crack Latest 2025
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
PPTX
FL Studio Producer Edition Crack 24 + Latest Version [2025]
PPTX
Adobe Photoshop 2025 Cracked Latest Version
PPTX
Python Lecture 7
PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
Python programming : Exceptions
Python Exception handling using Try-Except-Finally
Exception handling.pptxnn h
Unit 4-Exception Handling in Python.pdf
EXCEPTION HANDLING class 12th computer science.pptx
Exception Handling in python programming.pptx
Exception Handling in Python programming.pptx
Exception Handling in Python Programming.pptx
Python_Exception_Handling_Presentation.pptx
Exception handling in python
Exception Handling on 22nd March 2022.ppt
EXCEPTION HANDLING - PYTHON COMPUTER SCIENCE
Download Wondershare Filmora Crack Latest 2025
lecs101.pdfgggggggggggggggggggddddddddddddb
FL Studio Producer Edition Crack 24 + Latest Version [2025]
Adobe Photoshop 2025 Cracked Latest Version
Python Lecture 7
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt

More from P3 InfoTech Solutions Pvt. Ltd.

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

Python Programming Essentials - M21 - Exception Handling

  • 1.
    http://www.skillbrew.com/SkillbrewTalent brewed bythe industry itselfException Handling in pythonPavan Verma@YinYangPavanFounder, P3 InfoTech Solutions Pvt. Ltd.1Python Programming Essentials
  • 2.
    © SkillBrew http://skillbrew.comContentsExceptions Throwing and catching exceptions try except try except else try except finally Common python exceptions2
  • 3.
    © SkillBrew http://skillbrew.comWhatis an Exception? An exception is an error that happensduring execution of a program If an exception is not caught the programis terminated In Python, exceptions are triggeredautomatically on errors, and they can betriggered and intercepted by your code3
  • 4.
    © SkillBrew http://skillbrew.comExceptionsException handling has two steps:• Raising or Throwing• Catching Python provides 3 keywords to deal withexceptions :• raise• try• except4
  • 5.
    © SkillBrew http://skillbrew.comExceptions(2)Program to divide a constant by a numberdef divide(num):print 100/numif __name__ == '__main__':divide(0)OUPUT:ZeroDivisionError: integer division or modulo by zero5
  • 6.
    © SkillBrew http://skillbrew.comExceptionpropagation6>>> f1(0)Traceback (most recent call last):File "<pyshell#10>", line 1, in<module>f1(0)File "<pyshell#8>", line 2, in f1return f2(num)File "<pyshell#5>", line 2, in f2return f3(num)File "<pyshell#2>", line 3, in f3return constant/numZeroDivisionError: integer divisionor modulo by zero>>> def f3(num):constant = 100return constant/num>>> def f2(num):return f3(num)>>> def f1(num):return f2(num)>>> f1(10)10>>> f1(0)
  • 7.
    © SkillBrew http://skillbrew.comWhyuse exceptions Error handling: Python raises an exception wheneverit detects errors in program at runtime. You can catchand respond to errors in the code or Python’s defaultbehavior kicks in, stops the program and prints theerror message. Event notification: exceptions can also be used tosignal valid conditions without you having to passresult flags around a program7
  • 8.
  • 9.
    © SkillBrew http://skillbrew.comThrowingan exception9def avg(seq):result = 0for 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 valprint avg([1, 2, 4, 5])Output:3
  • 10.
    © SkillBrew http://skillbrew.comThrowingan exception10print 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 avgresult += convert(val)File "exceptions1.py", line 11, in convertraise ValueError('val type is not int')ValueError: val type is not int
  • 11.
    © SkillBrew http://skillbrew.comHandlingExceptions (try except block) In order to handle exceptions wrap the code in tryexceptdef divide(num):try:print 100/numexcept ZeroDivisionError:print("division by Zero not allowed")if __name__=='__main__':divide(0)Output:division by Zero not allowed11
  • 12.
    © SkillBrew http://skillbrew.comtryexcept else12try:# do somethingexcept:# handle exceptionelse:# executed only when there is no exceptionThe code in else block is only executed if there is noexception
  • 13.
    © SkillBrew http://skillbrew.comtryexcept else (2)def divide(num):try:result = 100/numexcept ZeroDivisionError:print('division by Zero not allowed')else:print “Result is %d" % (result)if __name__ == '__main__':divide(10)Output:Result is 1013
  • 14.
    © SkillBrew http://skillbrew.comtryexcept finally14try:# do somethingexcept:# handle exceptionfinally:# always executedThe code in finally block is always executed, nomatter what
  • 15.
    © SkillBrew http://skillbrew.comtryexcept finally (2)15def divide(num):try:result = 100/numexcept ZeroDivisionError:print('division by Zero not allowed')finally:print “Input was %d" % (num)if __name__ == '__main__':divide(0)Output:Division by Zero not allowedYour input was 0
  • 16.
    © SkillBrew http://skillbrew.comCommonPython ExceptionsException DescriptionIOError If the file cannot be openedImportError If python cannot find the moduleValueError Raised when a built-in operation orfunction receives an argument that hasthe right type but an inappropriate valueKeyError Raised when a mapping (dictionary) key isnot found in the set of existing keysIndentationError raised due to incorrect indentationSyntaxError Raised when the parser encounters asyntax error16
  • 17.
    © SkillBrew http://skillbrew.comCustomexceptionsclass MyException(Exception):passdef divide(num):try:return 100/numexcept ZeroDivisionError:raise MyException('Cannot divideby 0')17
  • 18.
    © SkillBrew http://skillbrew.comResourceshttp://doughellmann.com/2009/06/python-exception-handling-techniques.html18

[8]ページ先頭

©2009-2025 Movatter.jp