SlideShare a Scribd company logo
What is an Exception?
• An exception is an error that happens during execution of a
program.
• When that error occurs, Python generate an exception that
can be handled, which avoids your program to crash.
• Whenever an exception occurs the program halts the
execution and thus further code is not executed.
• Thus exception is that error which python script is unable to
tackle with.
Why use Exceptions?
• Exception in a code can also be handled.
• In case it is not handled, then the code is not executed further
and hence execution stops when exception occurs.
Hierarchy Of Exception
• ZeroDivisionError: Occurs when a number is divided by zero.
• NameError: It occurs when a name is not found. It may be
local or global.
• IndentationError: If incorrect indentation is given.
• IOError: It occurs when Input Output operation fails.
• EOFError: It occurs when end of file is reached and yet
operations are being performed
Exception Handling
• Python provides two very important features to handle any
unexpected error in your Python programs and to add
debugging capabilities in them-
1. Exception Handling.
2. Assertions.
Standard Exceptions
EXCEPTION NAME DESCRIPTION
Exception Base class for all exceptions
ArithmeticError Base class for all errors that occur for numeric
calculation.
ZeroDivisonError Raised when division or modulo by zero takes place for
all numeric types.
EOFError Raised when there is no input from either the
raw_input() or
input() function and the end of file is reached.
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution,
usually by pressing Ctrl+c.
NameError Raised when an identifier is not found in the local or
global namespace.
SyntaxError Raised when there is an error in Python syntax.
EXCEPTION NAME DESCRIPTION
IndentationError Raised when indentation is not specified properly.
TypeError Raised when an operation or function is attempted that
is invalid for the specified data type.
Exception Handling
• The suspicious code can be handled by using the try block.
• Enclose the code which raises an exception inside the try
block.
• The try block is followed by except clause.
• It is then further followed by statements which are executed
during exception and in case if exception does not occur.
Try •Code in which exception may occur
Raise •Raise the exception
Except •Catch if excepetion occurs
Declaring Multiple Exception
• Multiple Exceptions can be declared using the
same except statement:
try:
code
except (Exception1,Exception2,Exception3,..,ExceptionN):
execute this code in case any Exception of these occur.
else:
execute code in case no exception occurred.
try:
malicious code
except (Exception1):
execute code
except (Exception2):
execute code
....
....
except (ExceptionN):
execute code
else:
In case of no exception, execute the else block code.
try:
a=10/0
print (a)
except (ArithmeticError):
print( "This statement is raising an exception" )
else:
print ("Welcome“)
def fun(a,b):
try:
c=(a+b)/(a-b)
except (ArithmeticError):
print("EXCEPTION OCCUR")
else:
print(c)
finally:
print("End of the world")
# Driver program to test above function
fun(2.0, 3.0) # -5.0 End of the world
fun(3.0, 3.0) # EXCEPTION OCCUR End of the world
Argument of an Exception
• An exception can have an argument, which is a value that gives
additional information about the problem.
• The contents of the argument vary by exception.
• You capture an exception's argument by supplying a variable in
the except clause as follows-
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
Example 1
def fun(a):
try:
return int(a)
except ValueError as VE:
print("argument is not a number",VE)
fun(11) # 11
fun("string")
#argument is not a number invalid literal for int() with base 10: 'string’
Example 2
def fun(a,b):
c= a/b
return c
try:
fun("a","b")
except TypeError as VE:
print("Exception: ",VE)
Output:
Exception: unsupported operand type(s) for /: 'str' and 'str'
Raising Exception
• The raise statement allows the programmer to force a specific
exception to occur.
• The sole argument in raise indicates the exception to be raised.
• This must be either an exception instance or an exception class (a class
that derives from Exception).
# Program to depict Raising Exception
try:
raise NameError("Hey! are you sleeping!") # Raise Error
except NameError as NE:
print (NE)
try:
raise Exception("How are you")
except Exception as E:
print(E)
How are you
Explanation:
i) To raise an exception, raise statement is used.
It is followed by exception class name.
ii) Exception can be provided with a value(optional) that can be
given in the parenthesis. (here, Hey! are you sleeping!)
iii) To access the value "as" keyword is used.
“NE" is used as a reference variable which stores the value of
the exception.
User-defined Exceptions in Python
Creating User-defined Exception
• Programmers may name their own exceptions by creating a
new exception class.
• Exceptions need to be derived from the Exception class, either
directly or indirectly.
• Although not mandatory, most of the exceptions are named
as names that end in “Error” similar to naming of the
standard exceptions in python.
# A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occured: ',error.value)
class point(Exception):
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
p=point()
try:
if(p.x==0 and p.y ==0):
raise point()
except point as error:
print("point is ORIGIN",error)
else:
print(p)
OUTPUT:
point is ORIGIN (0,0)

More Related Content

PPTX
EXCEPTIONS-PYTHON.pptx RUNTIME ERRORS HANDLING
PDF
Unit 4-Exception Handling in Python.pdf
PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
DOCX
Exception handlingpdf
PPT
Exception Handling on 22nd March 2022.ppt
PPTX
Python Unit II.pptx
PPTX
Exception Handling in python programming.pptx
PPTX
Exception handling with python class 12.pptx
EXCEPTIONS-PYTHON.pptx RUNTIME ERRORS HANDLING
Unit 4-Exception Handling in Python.pdf
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
Exception handlingpdf
Exception Handling on 22nd March 2022.ppt
Python Unit II.pptx
Exception Handling in python programming.pptx
Exception handling with python class 12.pptx

Similar to Exception Handling in Python Programming.pptx (20)

PPT
PPTX
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
PPTX
Python Exception Handling
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
PPTX
Python Exceptions Powerpoint Presentation
PDF
Exception handling in python
PPTX
Python Lecture 7
PPT
Exception handling in python and how to handle it
PDF
Python programming : Exceptions
PPT
Exception Handling using Python Libraries
PPTX
Python Exception Handling (Python Course)
PDF
Python Programming - X. Exception Handling and Assertions
PPTX
Error and exception in python
PPT
Py-Slides-9.ppt
PPTX
Exception handling.pptxnn h
PPTX
Python_Exception_Handling_Presentation.pptx
PPTX
Exception Handling.pptx
PPTX
Exception Handling in Python
PPTX
Exception handling.pptx
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
Python Exception Handling
lecs101.pdfgggggggggggggggggggddddddddddddb
Python Exceptions Powerpoint Presentation
Exception handling in python
Python Lecture 7
Exception handling in python and how to handle it
Python programming : Exceptions
Exception Handling using Python Libraries
Python Exception Handling (Python Course)
Python Programming - X. Exception Handling and Assertions
Error and exception in python
Py-Slides-9.ppt
Exception handling.pptxnn h
Python_Exception_Handling_Presentation.pptx
Exception Handling.pptx
Exception Handling in Python
Exception handling.pptx
Ad

More from vinayagrawal71 (8)

PPT
Recursion and Lambda Functions in python.ppt
PPT
Sets in the python programming language.ppt
PPT
File Handling in python programming .ppt
PPTX
Exceptional Handling in the python .pptx
PPTX
Exception Handling in Python programming.pptx
PPT
Dictionarys in python programming language.ppt
PPTX
11Exceptional Handling In Python Language.pptx
PPT
File Handling in Python Programming .ppt
Recursion and Lambda Functions in python.ppt
Sets in the python programming language.ppt
File Handling in python programming .ppt
Exceptional Handling in the python .pptx
Exception Handling in Python programming.pptx
Dictionarys in python programming language.ppt
11Exceptional Handling In Python Language.pptx
File Handling in Python Programming .ppt
Ad

Recently uploaded (20)

PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
DOCX
573137875-Attendance-Management-System-original
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Well-logging-methods_new................
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
additive manufacturing of ss316l using mig welding
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
R24 SURVEYING LAB MANUAL for civil enggi
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
573137875-Attendance-Management-System-original
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Well-logging-methods_new................
bas. eng. economics group 4 presentation 1.pptx
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
additive manufacturing of ss316l using mig welding
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
OOP with Java - Java Introduction (Basics)
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Embodied AI: Ushering in the Next Era of Intelligent Systems
Mitigating Risks through Effective Management for Enhancing Organizational Pe...

Exception Handling in Python Programming.pptx

  • 1. What is an Exception? • An exception is an error that happens during execution of a program. • When that error occurs, Python generate an exception that can be handled, which avoids your program to crash. • Whenever an exception occurs the program halts the execution and thus further code is not executed. • Thus exception is that error which python script is unable to tackle with.
  • 2. Why use Exceptions? • Exception in a code can also be handled. • In case it is not handled, then the code is not executed further and hence execution stops when exception occurs.
  • 3. Hierarchy Of Exception • ZeroDivisionError: Occurs when a number is divided by zero. • NameError: It occurs when a name is not found. It may be local or global. • IndentationError: If incorrect indentation is given. • IOError: It occurs when Input Output operation fails. • EOFError: It occurs when end of file is reached and yet operations are being performed
  • 4. Exception Handling • Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them- 1. Exception Handling. 2. Assertions.
  • 5. Standard Exceptions EXCEPTION NAME DESCRIPTION Exception Base class for all exceptions ArithmeticError Base class for all errors that occur for numeric calculation. ZeroDivisonError Raised when division or modulo by zero takes place for all numeric types. EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached. ImportError Raised when an import statement fails. KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c. NameError Raised when an identifier is not found in the local or global namespace. SyntaxError Raised when there is an error in Python syntax.
  • 6. EXCEPTION NAME DESCRIPTION IndentationError Raised when indentation is not specified properly. TypeError Raised when an operation or function is attempted that is invalid for the specified data type.
  • 7. Exception Handling • The suspicious code can be handled by using the try block. • Enclose the code which raises an exception inside the try block. • The try block is followed by except clause. • It is then further followed by statements which are executed during exception and in case if exception does not occur.
  • 8. Try •Code in which exception may occur Raise •Raise the exception Except •Catch if excepetion occurs
  • 9. Declaring Multiple Exception • Multiple Exceptions can be declared using the same except statement: try: code except (Exception1,Exception2,Exception3,..,ExceptionN): execute this code in case any Exception of these occur. else: execute code in case no exception occurred.
  • 10. try: malicious code except (Exception1): execute code except (Exception2): execute code .... .... except (ExceptionN): execute code else: In case of no exception, execute the else block code.
  • 11. try: a=10/0 print (a) except (ArithmeticError): print( "This statement is raising an exception" ) else: print ("Welcome“)
  • 12. def fun(a,b): try: c=(a+b)/(a-b) except (ArithmeticError): print("EXCEPTION OCCUR") else: print(c) finally: print("End of the world") # Driver program to test above function fun(2.0, 3.0) # -5.0 End of the world fun(3.0, 3.0) # EXCEPTION OCCUR End of the world
  • 13. Argument of an Exception • An exception can have an argument, which is a value that gives additional information about the problem. • The contents of the argument vary by exception. • You capture an exception's argument by supplying a variable in the except clause as follows- try: You do your operations here ...................... except ExceptionType as Argument: You can print value of Argument here...
  • 14. Example 1 def fun(a): try: return int(a) except ValueError as VE: print("argument is not a number",VE) fun(11) # 11 fun("string") #argument is not a number invalid literal for int() with base 10: 'string’
  • 15. Example 2 def fun(a,b): c= a/b return c try: fun("a","b") except TypeError as VE: print("Exception: ",VE) Output: Exception: unsupported operand type(s) for /: 'str' and 'str'
  • 16. Raising Exception • The raise statement allows the programmer to force a specific exception to occur. • The sole argument in raise indicates the exception to be raised. • This must be either an exception instance or an exception class (a class that derives from Exception). # Program to depict Raising Exception try: raise NameError("Hey! are you sleeping!") # Raise Error except NameError as NE: print (NE)
  • 17. try: raise Exception("How are you") except Exception as E: print(E) How are you
  • 18. Explanation: i) To raise an exception, raise statement is used. It is followed by exception class name. ii) Exception can be provided with a value(optional) that can be given in the parenthesis. (here, Hey! are you sleeping!) iii) To access the value "as" keyword is used. “NE" is used as a reference variable which stores the value of the exception.
  • 19. User-defined Exceptions in Python Creating User-defined Exception • Programmers may name their own exceptions by creating a new exception class. • Exceptions need to be derived from the Exception class, either directly or indirectly. • Although not mandatory, most of the exceptions are named as names that end in “Error” similar to naming of the standard exceptions in python.
  • 20. # A python program to create user-defined exception # class MyError is derived from super class Exception class MyError(Exception): # Constructor or Initializer def __init__(self, value): self.value = value # __str__ is to print() the value def __str__(self): return(repr(self.value))
  • 21. try: raise(MyError(3*2)) # Value of Exception is stored in error except MyError as error: print('A New Exception occured: ',error.value)
  • 22. class point(Exception): def __init__(self,x=0,y=0): self.x=x self.y=y def __str__(self): return "({0},{1})".format(self.x, self.y)
  • 23. p=point() try: if(p.x==0 and p.y ==0): raise point() except point as error: print("point is ORIGIN",error) else: print(p) OUTPUT: point is ORIGIN (0,0)