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)
Ad

More Related Content

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

ACP - Week - 9.pptx
ACP - Week - 9.pptxACP - Week - 9.pptx
ACP - Week - 9.pptx
funnyvideosbysam
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
gandra jeeshitha
 
exception handling.pptx
exception handling.pptxexception handling.pptx
exception handling.pptx
AbinayaC11
 
Exception handling.pptxnn h
Exception handling.pptxnn                                        hException handling.pptxnn                                        h
Exception handling.pptxnn h
sabarivelan111007
 
exceptioninpython.pptx
exceptioninpython.pptxexceptioninpython.pptx
exceptioninpython.pptx
SulekhJangra
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptxException handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
Python Exceptions Powerpoint Presentation
Python Exceptions Powerpoint PresentationPython Exceptions Powerpoint Presentation
Python Exceptions Powerpoint Presentation
mitchellblack733
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
DrJasmineBeulahG
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
43c
43c43c
43c
Sireesh K
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Exception Handling in Python - Rik van Achterberg & Tim Muller
Exception Handling in Python - Rik van Achterberg & Tim MullerException Handling in Python - Rik van Achterberg & Tim Muller
Exception Handling in Python - Rik van Achterberg & Tim Muller
Byte
 
Python exceptions
Python exceptionsPython exceptions
Python exceptions
rikbyte
 
JAVA Exception Handling in java programing
JAVA Exception Handling in java programingJAVA Exception Handling in java programing
JAVA Exception Handling in java programing
rathoreravindra2112
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
exception handling.pptx
exception handling.pptxexception handling.pptx
exception handling.pptx
AbinayaC11
 
exceptioninpython.pptx
exceptioninpython.pptxexceptioninpython.pptx
exceptioninpython.pptx
SulekhJangra
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptxException handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
Python Exceptions Powerpoint Presentation
Python Exceptions Powerpoint PresentationPython Exceptions Powerpoint Presentation
Python Exceptions Powerpoint Presentation
mitchellblack733
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
DrJasmineBeulahG
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Exception Handling in Python - Rik van Achterberg & Tim Muller
Exception Handling in Python - Rik van Achterberg & Tim MullerException Handling in Python - Rik van Achterberg & Tim Muller
Exception Handling in Python - Rik van Achterberg & Tim Muller
Byte
 
Python exceptions
Python exceptionsPython exceptions
Python exceptions
rikbyte
 
JAVA Exception Handling in java programing
JAVA Exception Handling in java programingJAVA Exception Handling in java programing
JAVA Exception Handling in java programing
rathoreravindra2112
 

Recently uploaded (20)

ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Ad

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)