SlideShare a Scribd company logo
Exception
• When writing a program we more often than not will encounter errors.
• Error caused by not following the proper structure (syntax) of the
language is called syntax error parsing error.
>>> if a<3
Syntax Error: invalid syntax
• We can notice here that a colon is missing in the if statement.
• Errors can also occur at runtime and these are called exceptions
• They occur for example
– When a file we try to open does not exist (FileNotFoundError)
– Dividing a number by Zero (ZeroDivisionError)
– Module we try to import is not found (ImportError) etc.
• Whenever these type of runtime error occur, Python creates an exception
object. If not handled properly it prints a traceback to that error along
with some details about why that error occurred.
Exception
>>> 1/0
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
>>> open('i.txt')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
open('i.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'i.txt'
Built-in Exceptions
• An exception is a value (object) that is raised (“thrown”) signaling that an
unexpected or “exceptional” situation has occurred.
• Python contains a predefined set of exceptions referred to as Standard
Exceptions.
Exceptions Description
ImportError Raised when an import (or from … import) statement fails
IndexError Raised when a sequence index out of range
NameError Raised when a local or global name is not found
TypeError Raised when an operation or function is applied to an
object of inappropriate type
ValueError Raised when a built in operation or function is applied to
an appropriate type, but of inappropriate value
IOError Raised when an input/output operation fails (eg: “file not
found”)
Standard Exceptions
• The standard exceptions are defined within the exceptions module of the
python standard library, which is automatically imported into python
programs.
• We have seen a number of these exceptions before in our programming.
• Raising an exception is a way for a function to inform its client a problem has
occurred that the function itself cannot handle.
>>> lst[3]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
lst[3]
IndexError: list index out of range
>>> lst1[0]
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
lst1[0]
NameError: name 'lst1' is not defined
>>> int('45')
45
>>> 3+'7'
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
3+'7'
TypeError: unsupported operand type(s) for +:
'int' and 'str‘
>>> int('45.9')
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
int('45.9')
ValueError: invalid literal for int() with base 10:
'45.9'
The propagation of raised exceptions
• Raised exceptions are not required to be handled in python.
• When an exception is raised and not handled by the client code, it is
automatically propagated back to the clients calling code (and its calling
code etc) until handled.
• If an exception is thrown all the way back to the top level (main module)
and not handled, then the program terminates and displays the details of
the exception as shown below.
The propagation of raised exceptions
• If function A calls function B which in turn calls function C and which in
turn calls function D and an exception occurs in function D, if it is not
handled in D, the exception passes to C and then to B and then to A.
• If never handled an error message is split out and program come to a
sudden unexcepted halt.
Exception Handling
• Catching Exception:
– In python, exception can be handled using a try statement.
– A critical operation which can raise exception is placed inside the try clause and the code
that handles exception is written in except clause.
– It is upto us what operations we perform once we have caught the exception.
import sys
lst = ['x',5,0]
for e in lst:
try:
print("The element is ",e)
r = 1 / int(e)
print("The reciprocal of ", e," is ",r)
except:
print("Oops! ", sys.exc_info()[0],"
occurred")
OUTPUT:
The element is x
Oops! <class 'ValueError'> occurred
The element is 5
The reciprocal of 5 is 0.2
The element is 0
Oops! <class 'ZeroDivisionError'>
occurred
sys.exc_info()
• This function returns a tuple of three values that give information about
the exception that is currently being handled.
• The information returned is specific both to the current thread and to the
current stack frame.
• If the current stack frame is not handling an exception, the information is
taken from the calling stack frame or its caller and so in until a stack frame
is found that is handling an exception.
• Here “handling an exception” is defined as “executing or having executed
an except clause”.
• If no exception is being handled anywhere on the stack, a tuple containing
three None values is returned.
• Otherwise, the values returned on (type, value, traceback)
– type:- gets the exception type of the exception being handled (a class object)
– value:- gets the exception parameter
– traceback:- gets a traceback object
Exception Handling
import sys
lst = ['x',5,0]
for e in lst:
try:
print("The element is ",e)
r = 1 / int(e)
print("The reciprocal of ", e," is ",r)
except:
print("Oops! ", sys.exc_info(),"
occurred")
OUTPUT:
The element is x
Oops! (<class 'ValueError'>,
ValueError("invalid literal for int() with
base 10: 'x'"), <traceback object at
0x000001A994DFA4C8>) occurred
The element is 5
The reciprocal of 5 is 0.2
The element is 0
Oops! (<class 'ZeroDivisionError'>,
ZeroDivisionError('division by zero'),
<traceback object at
0x000001A994DFA4C8>) occurred
• If no exception occurs, except block is skipped and normal flow continues.
• But if any exception occurs it is caught by the except block.
The try and except block
• In python, exceptions are handled using the try and except block.
• Python, executes the try block as a normal part of the program.
• When an error occurs during its exception, the rest of the block is skipped
and except block is executed.
Example 1:
i=1/0
print("i = ",i)
print("After division")
Traceback (most recent call last):
File
"C:/Users/swathy/AppData/Local/Programs/Pyt
hon/Python37/files1.py", line 1, in <module>
i=1/0
ZeroDivisionError: division by zero
Exception Handling - Example
Example 2:
try:
i=1/0
print("i = ",i)
except:
print("Some exception occured")
print("After division")
OUTPUT:
Some exception occured
After division
import sys
try:
i=1/0
print("i = ",i)
except:
print(sys.exc_info()[0]," occured.")
print("After division")
OUTPUT:
<class 'ZeroDivisionError'> occured.
After division
Example 3:
Exception Handling - Example
• Python don’t just handle exceptions if they occur immediately in the try
block, but also if they occur inside functions that are called in the try
block.
import sys
def func():
i=1/0
print("Inside function")
try:
func()
print("Inside try block")
except:
print(sys.exc_info()[0]," occured.")
print("After function call inside main module")
OUTPUT:
<class 'ZeroDivisionError'> occured.
After function call inside main module
Example 4:
Catch Multiple Exceptions
• We can define as many except blocks as we want to catch and handle
specific exceptions.
try:
print(int('45.6'))
except (ZeroDivisionError, ValueError):
print("Attempt to divide by zero")
except:
print("Something else went wrong")
OUTPUT:
Attempt to divide by zero
ZeroDivisionError, ValueError
Example 4:
The Else Clause
• The try except block has an optional else clause.
• The else clause is executed only if no exceptions are raised
Example:
try:
x = 1/2
print("x = ",x)
except:
print("Something went wrong")
else:
print("Nothing went wrong")
x = 0.5
Nothing went wrong
The Finally Clause
• The try except block has an optional finally clause.
• The finally clause is always executed, whether an exception has occurred or not
The Finally Clause
• We can define as many except blocks as we want to catch and handle
specific exceptions.
try:
x = 1/0
except:
print("Something went wrong")
finally:
print("Always executes this")
OUTPUT:
Something went wrong
Always executes this
Example:
Example:
try:
f=open('text1.txt')
print(f.read())
except:
print("Something went wrong")
finally:
f.close()
OUTPUT:
Something went wrong
Always executes this
Raising an Exception
• If we want to raise an exception when a certain condition occurs, use raise
keyword.
• You can define what kind of error to raise, and the text to print to the user.
print("Exception handling concepts")
raise NameError("An exception occured")
Example:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
OUTPUT:
Traceback (most recent call last):
File "keyword_raise.py", line 4, in
<module>
raise TypeError("Only integers are
allowed")
TypeError: Only integers are allowed

More Related Content

PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
PPTX
Exception handling.pptxnn h
sabarivelan111007
 
PPT
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
PPTX
Exception handling with python class 12.pptx
PreeTVithule1
 
PPT
Exception handling in python and how to handle it
s6901412
 
PPT
Exception Handling using Python Libraries
mmvrm
 
DOCX
Exception handlingpdf
gandra jeeshitha
 
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
svijaycdac
 
Exception handling.pptxnn h
sabarivelan111007
 
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
Exception handling with python class 12.pptx
PreeTVithule1
 
Exception handling in python and how to handle it
s6901412
 
Exception Handling using Python Libraries
mmvrm
 
Exception handlingpdf
gandra jeeshitha
 

Similar to Exception Handling in python programming.pptx (20)

PPT
Py-Slides-9.ppt
wulanpermatasari27
 
PPTX
Exception Handling.pptx
Pavan326406
 
PPT
Exception
Navaneethan Naveen
 
PPTX
Exception Handling in Python Programming.pptx
vinayagrawal71
 
PPTX
Exception Handling in Python programming.pptx
vinayagrawal71
 
PDF
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
PPTX
Error and exception in python
junnubabu
 
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
PPTX
Exception handling.pptx
NISHASOMSCS113
 
PPTX
EXCEPTIONS-PYTHON.pptx RUNTIME ERRORS HANDLING
NagarathnaRajur2
 
PPTX
Python Lecture 7
Inzamam Baig
 
PDF
Unit 4-Exception Handling in Python.pdf
Harsha Patil
 
PPTX
exceptioninpython.pptx
SulekhJangra
 
PPTX
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
xaybhagfsus
 
PPTX
Python Exception Handling
Megha V
 
PDF
Exception handling in python
Lifna C.S
 
PPTX
Python Exceptions Powerpoint Presentation
mitchellblack733
 
PPTX
exception handling.pptx
AbinayaC11
 
PPTX
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
PPTX
Exception Handling in Python
DrJasmineBeulahG
 
Py-Slides-9.ppt
wulanpermatasari27
 
Exception Handling.pptx
Pavan326406
 
Exception Handling in Python Programming.pptx
vinayagrawal71
 
Exception Handling in Python programming.pptx
vinayagrawal71
 
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
Error and exception in python
junnubabu
 
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
Exception handling.pptx
NISHASOMSCS113
 
EXCEPTIONS-PYTHON.pptx RUNTIME ERRORS HANDLING
NagarathnaRajur2
 
Python Lecture 7
Inzamam Baig
 
Unit 4-Exception Handling in Python.pdf
Harsha Patil
 
exceptioninpython.pptx
SulekhJangra
 
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
xaybhagfsus
 
Python Exception Handling
Megha V
 
Exception handling in python
Lifna C.S
 
Python Exceptions Powerpoint Presentation
mitchellblack733
 
exception handling.pptx
AbinayaC11
 
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
Exception Handling in Python
DrJasmineBeulahG
 
Ad

Recently uploaded (20)

PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PDF
High Ground Student Revision Booklet Preview
jpinnuck
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
High Ground Student Revision Booklet Preview
jpinnuck
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Understanding operators in c language.pptx
auteharshil95
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Landforms and landscapes data surprise preview
jpinnuck
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Ad

Exception Handling in python programming.pptx

  • 1. Exception • When writing a program we more often than not will encounter errors. • Error caused by not following the proper structure (syntax) of the language is called syntax error parsing error. >>> if a<3 Syntax Error: invalid syntax • We can notice here that a colon is missing in the if statement. • Errors can also occur at runtime and these are called exceptions • They occur for example – When a file we try to open does not exist (FileNotFoundError) – Dividing a number by Zero (ZeroDivisionError) – Module we try to import is not found (ImportError) etc. • Whenever these type of runtime error occur, Python creates an exception object. If not handled properly it prints a traceback to that error along with some details about why that error occurred.
  • 2. Exception >>> 1/0 Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> 1/0 ZeroDivisionError: division by zero >>> open('i.txt') Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> open('i.txt') FileNotFoundError: [Errno 2] No such file or directory: 'i.txt'
  • 3. Built-in Exceptions • An exception is a value (object) that is raised (“thrown”) signaling that an unexpected or “exceptional” situation has occurred. • Python contains a predefined set of exceptions referred to as Standard Exceptions. Exceptions Description ImportError Raised when an import (or from … import) statement fails IndexError Raised when a sequence index out of range NameError Raised when a local or global name is not found TypeError Raised when an operation or function is applied to an object of inappropriate type ValueError Raised when a built in operation or function is applied to an appropriate type, but of inappropriate value IOError Raised when an input/output operation fails (eg: “file not found”)
  • 4. Standard Exceptions • The standard exceptions are defined within the exceptions module of the python standard library, which is automatically imported into python programs. • We have seen a number of these exceptions before in our programming. • Raising an exception is a way for a function to inform its client a problem has occurred that the function itself cannot handle. >>> lst[3] Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> lst[3] IndexError: list index out of range >>> lst1[0] Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> lst1[0] NameError: name 'lst1' is not defined >>> int('45') 45 >>> 3+'7' Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> 3+'7' TypeError: unsupported operand type(s) for +: 'int' and 'str‘ >>> int('45.9') Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> int('45.9') ValueError: invalid literal for int() with base 10: '45.9'
  • 5. The propagation of raised exceptions • Raised exceptions are not required to be handled in python. • When an exception is raised and not handled by the client code, it is automatically propagated back to the clients calling code (and its calling code etc) until handled. • If an exception is thrown all the way back to the top level (main module) and not handled, then the program terminates and displays the details of the exception as shown below.
  • 6. The propagation of raised exceptions • If function A calls function B which in turn calls function C and which in turn calls function D and an exception occurs in function D, if it is not handled in D, the exception passes to C and then to B and then to A. • If never handled an error message is split out and program come to a sudden unexcepted halt.
  • 7. Exception Handling • Catching Exception: – In python, exception can be handled using a try statement. – A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause. – It is upto us what operations we perform once we have caught the exception. import sys lst = ['x',5,0] for e in lst: try: print("The element is ",e) r = 1 / int(e) print("The reciprocal of ", e," is ",r) except: print("Oops! ", sys.exc_info()[0]," occurred") OUTPUT: The element is x Oops! <class 'ValueError'> occurred The element is 5 The reciprocal of 5 is 0.2 The element is 0 Oops! <class 'ZeroDivisionError'> occurred
  • 8. sys.exc_info() • This function returns a tuple of three values that give information about the exception that is currently being handled. • The information returned is specific both to the current thread and to the current stack frame. • If the current stack frame is not handling an exception, the information is taken from the calling stack frame or its caller and so in until a stack frame is found that is handling an exception. • Here “handling an exception” is defined as “executing or having executed an except clause”. • If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. • Otherwise, the values returned on (type, value, traceback) – type:- gets the exception type of the exception being handled (a class object) – value:- gets the exception parameter – traceback:- gets a traceback object
  • 9. Exception Handling import sys lst = ['x',5,0] for e in lst: try: print("The element is ",e) r = 1 / int(e) print("The reciprocal of ", e," is ",r) except: print("Oops! ", sys.exc_info()," occurred") OUTPUT: The element is x Oops! (<class 'ValueError'>, ValueError("invalid literal for int() with base 10: 'x'"), <traceback object at 0x000001A994DFA4C8>) occurred The element is 5 The reciprocal of 5 is 0.2 The element is 0 Oops! (<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x000001A994DFA4C8>) occurred • If no exception occurs, except block is skipped and normal flow continues. • But if any exception occurs it is caught by the except block.
  • 10. The try and except block • In python, exceptions are handled using the try and except block. • Python, executes the try block as a normal part of the program. • When an error occurs during its exception, the rest of the block is skipped and except block is executed. Example 1: i=1/0 print("i = ",i) print("After division") Traceback (most recent call last): File "C:/Users/swathy/AppData/Local/Programs/Pyt hon/Python37/files1.py", line 1, in <module> i=1/0 ZeroDivisionError: division by zero
  • 11. Exception Handling - Example Example 2: try: i=1/0 print("i = ",i) except: print("Some exception occured") print("After division") OUTPUT: Some exception occured After division import sys try: i=1/0 print("i = ",i) except: print(sys.exc_info()[0]," occured.") print("After division") OUTPUT: <class 'ZeroDivisionError'> occured. After division Example 3:
  • 12. Exception Handling - Example • Python don’t just handle exceptions if they occur immediately in the try block, but also if they occur inside functions that are called in the try block. import sys def func(): i=1/0 print("Inside function") try: func() print("Inside try block") except: print(sys.exc_info()[0]," occured.") print("After function call inside main module") OUTPUT: <class 'ZeroDivisionError'> occured. After function call inside main module Example 4:
  • 13. Catch Multiple Exceptions • We can define as many except blocks as we want to catch and handle specific exceptions. try: print(int('45.6')) except (ZeroDivisionError, ValueError): print("Attempt to divide by zero") except: print("Something else went wrong") OUTPUT: Attempt to divide by zero ZeroDivisionError, ValueError Example 4:
  • 14. The Else Clause • The try except block has an optional else clause. • The else clause is executed only if no exceptions are raised Example: try: x = 1/2 print("x = ",x) except: print("Something went wrong") else: print("Nothing went wrong") x = 0.5 Nothing went wrong
  • 15. The Finally Clause • The try except block has an optional finally clause. • The finally clause is always executed, whether an exception has occurred or not
  • 16. The Finally Clause • We can define as many except blocks as we want to catch and handle specific exceptions. try: x = 1/0 except: print("Something went wrong") finally: print("Always executes this") OUTPUT: Something went wrong Always executes this Example: Example: try: f=open('text1.txt') print(f.read()) except: print("Something went wrong") finally: f.close() OUTPUT: Something went wrong Always executes this
  • 17. Raising an Exception • If we want to raise an exception when a certain condition occurs, use raise keyword. • You can define what kind of error to raise, and the text to print to the user. print("Exception handling concepts") raise NameError("An exception occured") Example: x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed") OUTPUT: Traceback (most recent call last): File "keyword_raise.py", line 4, in <module> raise TypeError("Only integers are allowed") TypeError: Only integers are allowed