SlideShare a Scribd company logo
PYTHON
AGENDA
Exception
Handling an exception
What is Exception?
 An exception is an event, which occurs during
the execution of a program, that disrupts the normal flow
of the program's instructions.
 In general, when a Python script encounters a
situation that it can't cope with, it raises an exception..
 When a Python script raises an exception, it
must either handle the exception immediately
otherwise it would terminate and come out.
Exceptions Types
EXCEPTION NAME DESCRIPTION
ZeroDivisonError Raised when division or modulo by zero
takes place for all numeric types.
ImportError Raised when an import statement fails.
IOError Raised when an input/ output operation
fails, the open() function when trying to
open a file that does not exist.
SyntaxError Raised when there is an error in Python
syntax.
IndentationError Raised when indentation is not specified
properly.
Handling an exception
If any suspicious code that may raise an exception
suspicious code in a try: block. After the try: block,
include an except: statement, followed by a block of
code
which handles the problem as elegantly as possible.
• SYNTAX:
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
 A single try statement can have multiple except statements.
This is useful when the try block contains statements that may
throw different types of exceptions.
 Also provide a generic except clause, which handles any
exception.
 After the except clause(s), you can include an else-clause. The
code in the else-block executes if the code in the try: block does
not raise an exception.
• Example
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can't find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Output:
Written content in the file successfully
• The except clause with multiple exceptions:
try:
You do your operations here;
......................
except(Exception1, Exception2,...ExceptionN):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
• The try-finally clause:
The finally block is a place to put any code that must
execute, whether the try-block raised an exception or not
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can't find file or read data"
If you do not have permission to open the file in writing mode,
Output:
Error: can't find file or read data
• Raising an exceptions:
Raise an exceptions in several ways by using the raise
statement.
SYNTAX:
raise Exception [ args ]
Here, Exception is the type of exception (for example,
NameError) and argument is a value for the exception
argument. The argument is optional; if not supplied, the
exception argument is None.
• Example:
level = 1
if level < 2:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
• In order to catch an exception, an "except" clause must refer to
the same exception thrown either class object or simple string.
For example, to capture above exception, we must write our
except clause as follows:
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
Exception

More Related Content

What's hot

Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
Lifna C.S
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Presentation1
Presentation1Presentation1
Presentation1
Anul Chaudhary
 
43c
43c43c
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
exception handling in java
exception handling in java exception handling in java
exception handling in java aptechsravan
 

What's hot (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Presentation1
Presentation1Presentation1
Presentation1
 
43c
43c43c
43c
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 

Similar to Exception

Exception Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptException Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
wulanpermatasari27
 
EXCEPTION HANDLING IN PYTHON For students .py.pptx
EXCEPTION  HANDLING IN PYTHON For students .py.pptxEXCEPTION  HANDLING IN PYTHON For students .py.pptx
EXCEPTION HANDLING IN PYTHON For students .py.pptx
MihirBhardwaj3
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
Inzamam Baig
 
exceptioninpython.pptx
exceptioninpython.pptxexceptioninpython.pptx
exceptioninpython.pptx
SulekhJangra
 
ACP - Week - 9.pptx
ACP - Week - 9.pptxACP - Week - 9.pptx
ACP - Week - 9.pptx
funnyvideosbysam
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
Exception handling
Exception handlingException handling
Exception handling
Sandeep Rawat
 
Exception handling
Exception handlingException handling
Exception handling
Abishek Purushothaman
 
exception handling.pptx
exception handling.pptxexception handling.pptx
exception handling.pptx
AbinayaC11
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
junnubabu
 
41c
41c41c
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
imran khan
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
sarthakgithub
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exception handling.pptx
Exception handling.pptxException handling.pptx
Exception handling.pptx
NISHASOMSCS113
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
Pavan326406
 

Similar to Exception (20)

Exception Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.pptException Handling on 22nd March 2022.ppt
Exception Handling on 22nd March 2022.ppt
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
 
EXCEPTION HANDLING IN PYTHON For students .py.pptx
EXCEPTION  HANDLING IN PYTHON For students .py.pptxEXCEPTION  HANDLING IN PYTHON For students .py.pptx
EXCEPTION HANDLING IN PYTHON For students .py.pptx
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
exceptioninpython.pptx
exceptioninpython.pptxexceptioninpython.pptx
exceptioninpython.pptx
 
ACP - Week - 9.pptx
ACP - Week - 9.pptxACP - Week - 9.pptx
ACP - Week - 9.pptx
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
exception handling.pptx
exception handling.pptxexception handling.pptx
exception handling.pptx
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Exceptions
ExceptionsExceptions
Exceptions
 
41c
41c41c
41c
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception handling.pptx
Exception handling.pptxException handling.pptx
Exception handling.pptx
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 

More from Navaneethan Naveen

Class inheritance 13 session - SHAN
Class inheritance 13 session - SHANClass inheritance 13 session - SHAN
Class inheritance 13 session - SHANNavaneethan Naveen
 
Python session.11 By Shanmugam
Python session.11 By ShanmugamPython session.11 By Shanmugam
Python session.11 By ShanmugamNavaneethan Naveen
 
Networking session-4-final by aravind.R
Networking session-4-final by aravind.RNetworking session-4-final by aravind.R
Networking session-4-final by aravind.RNavaneethan Naveen
 
WIN-ADCS-10
WIN-ADCS-10WIN-ADCS-10
WIN-ADCS-10
Navaneethan Naveen
 
Python session 10
Python session 10Python session 10
Python session 10
Navaneethan Naveen
 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamNavaneethan Naveen
 
Virtualization session 7 by Gugan
Virtualization session 7 by GuganVirtualization session 7 by Gugan
Virtualization session 7 by GuganNavaneethan Naveen
 
Virtualization s4.1
Virtualization s4.1Virtualization s4.1
Virtualization s4.1
Navaneethan Naveen
 
Python session 6
Python session 6Python session 6
Python session 6
Navaneethan Naveen
 
Gpo windows(4)
Gpo windows(4)Gpo windows(4)
Gpo windows(4)
Navaneethan Naveen
 
Windows session 5 : Basics of active directory
Windows session 5 : Basics of active directoryWindows session 5 : Basics of active directory
Windows session 5 : Basics of active directoryNavaneethan Naveen
 

More from Navaneethan Naveen (20)

Class inheritance 13 session - SHAN
Class inheritance 13 session - SHANClass inheritance 13 session - SHAN
Class inheritance 13 session - SHAN
 
Python session 12
Python session 12Python session 12
Python session 12
 
Python session 11
Python session 11Python session 11
Python session 11
 
V irtualisation.1
V irtualisation.1V irtualisation.1
V irtualisation.1
 
Python session.11 By Shanmugam
Python session.11 By ShanmugamPython session.11 By Shanmugam
Python session.11 By Shanmugam
 
Virtualisation-11
Virtualisation-11Virtualisation-11
Virtualisation-11
 
Networking session-4-final by aravind.R
Networking session-4-final by aravind.RNetworking session-4-final by aravind.R
Networking session-4-final by aravind.R
 
Networking session3
Networking session3Networking session3
Networking session3
 
WIN-ADCS-10
WIN-ADCS-10WIN-ADCS-10
WIN-ADCS-10
 
Python session 10
Python session 10Python session 10
Python session 10
 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugam
 
Python session 8
Python session 8Python session 8
Python session 8
 
Win 8th
Win 8thWin 8th
Win 8th
 
Virtualization session 8
Virtualization session 8Virtualization session 8
Virtualization session 8
 
Virtualization session 7 by Gugan
Virtualization session 7 by GuganVirtualization session 7 by Gugan
Virtualization session 7 by Gugan
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
 
Virtualization s4.1
Virtualization s4.1Virtualization s4.1
Virtualization s4.1
 
Python session 6
Python session 6Python session 6
Python session 6
 
Gpo windows(4)
Gpo windows(4)Gpo windows(4)
Gpo windows(4)
 
Windows session 5 : Basics of active directory
Windows session 5 : Basics of active directoryWindows session 5 : Basics of active directory
Windows session 5 : Basics of active directory
 

Recently uploaded

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

Exception

  • 3. What is Exception?  An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.  In general, when a Python script encounters a situation that it can't cope with, it raises an exception..  When a Python script raises an exception, it must either handle the exception immediately otherwise it would terminate and come out.
  • 4. Exceptions Types EXCEPTION NAME DESCRIPTION ZeroDivisonError Raised when division or modulo by zero takes place for all numeric types. ImportError Raised when an import statement fails. IOError Raised when an input/ output operation fails, the open() function when trying to open a file that does not exist. SyntaxError Raised when there is an error in Python syntax. IndentationError Raised when indentation is not specified properly.
  • 5. Handling an exception If any suspicious code that may raise an exception suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.
  • 6. • SYNTAX: Here is simple syntax of try....except...else blocks: try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.
  • 7.  A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.  Also provide a generic except clause, which handles any exception.  After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.
  • 8. • Example try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can't find file or read data" else: print "Written content in the file successfully" fh.close() Output: Written content in the file successfully
  • 9. • The except clause with multiple exceptions: try: You do your operations here; ...................... except(Exception1, Exception2,...ExceptionN): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block.
  • 10. • The try-finally clause: The finally block is a place to put any code that must execute, whether the try-block raised an exception or not try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print "Error: can't find file or read data" If you do not have permission to open the file in writing mode, Output: Error: can't find file or read data
  • 11. • Raising an exceptions: Raise an exceptions in several ways by using the raise statement. SYNTAX: raise Exception [ args ] Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.
  • 12. • Example: level = 1 if level < 2: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception
  • 13. • In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write our except clause as follows: try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here...