際際滷

際際滷Share a Scribd company logo
Chapter -6
Exception Handling
What is Exception?
Advantages of Exception Handling:
Unexpected situation or errors occur during the program execution is known as
Exception. This will lead to the termination of program execution. For this programmer
have no control on.
Egs. ATM machine running out of cash, When you try to open a file that does not exit in
that path. These type of anomalous situations are generally called exceptions and the way
to handle them is called exception handling.
Exception handling separates error handling code from normal code
It enhances readability
It stimulates the error handling to take place one at a time in one manner.
It makes for clear, robust, fault tolerant programs.
Some common examples of Exception  disturb normal flow of execution during run
time.
 Divide by zero errors
 Accessing th elements of an array/list beyond its range
 Index Error
 Invalid input
 Hard disk crash
 Opening of non-existing file
 Heap memory exhausted
Example:
>>>3/0
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
3/0
ZeroDivisionError: division by zero
This is generated by default exception handler of
python.
(i) Print out exception description
(ii) Prints the stack trace (where the exception
occurred
(iii) Causes the program termination.
Example:
>>>l1=[1,2,3]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
l1[4]
IndexError: list index out of range
Example:
>>>l1=[1,2,3]
>>>li[4]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
li[4]
NameError: name 'li' is not defined. Did you mean: 'l1'?
Concept of Exception handling:
1. Write a code in such a way that it raises some error flag every time something goes
wrong
2. Then trap this error flag and if this is spotted, call the error handling routine.
 Raising an imaginary error flag is called throwing or raising an error
 When error is thrown, the overall system responds by catching the error.
 The surrounding a block of error-sensitive-code-with-exception-handling is called trying
to execute a block.
Write code such that it
raises an error-flag
every time something
goes wrong
-------------------------------
Throw exception
If error flag
Is raised then
Call the error handling
routine
-------------------------------
Catch exception
Description Python terminology
An unexpected error that occurs during
runtime
Exception
A set of code that might have an
exception thrown in it
Try block
The process by which an exception is
generated and executing atatements that
try to resolve the problem
Catching
The block of code that attempts to deal
with the exception (ie. Problem)
Except clause for except/exception block
or catch block
The sequence of method calls that
brought control to the point where the
exception occurred
Stack trace
Terminology used with exception handling:
When to use Exception Handling:
 Processing exception situation
 Processing exception for components that cannot handle them directly
 Large projects that require uniform error-processing.
The segment of code where there is any possibility of error or exception, is placed
inside one block. The code to be executed in case the exception has occurred, is placed
inside another block.
Syntax of Exception Handling:
try:
#write here the code that may generate an exception
except:
#write code here about what to do when the exception has occurred
Example:
try:
a,b=int(input("enter a no")),int(input("enter a divisor"))
print(a/b)
except:
print("Division by Zero ! denominator must not be zero")
Output 1:
enter a no6
enter a divisor3
result of a/b 2.0
Output2:
enter a no6
enter a divisor0
Division by Zero ! denominator must not be zero
General built-in Python Exception:
Program to handle exception while opening a file
try:
myf=open("d:/myf.txt",'r')
print(myf.read())
except:
print("Error opening a file")
OUTPUT:
Hello python
The above output is displayed if the file has been opened for reading successfully.
Otherwise it shows Error opening a file
Exception raised because of TypeError and ValueError:
import traceback
try:
a=5
b=int(input("enter a no."))
print(a+b)
print(a+"five")
except ValueError:
print("arithmetic is not possible between a no. and string")
except TypeError:
print("cannot convert a string to a number")
Second argument of the except block:
try:
# code
Except <ExceptionName> as <exArgument>:
# handle error file
try:
print("result of 5/0=",5/5)
print("result of 5/0=",5/0)
except ZeroDivisionError as e:
print("Exception raised",e)
Output:
result of 5/0= 1.0
Exception raised division by zero
Handling multiple errors:
Multiple exception blocks  one for each exception raised.
This will give exact error message for a specific exception than having one common
error message for all exception.
try:
#:
except <exceptionName1>:
#:
except <exceptionName1>:
#:
except :
#:
else:
#if there is no exception then the statements in this block get executed.
Example:
try:
my_file=open('d:myf.txt')
my_line=my_file.readline()
my_int=int(s.strip())
my_calc=101/my_int
print(my_calc)
except IOError:
print('I/O error occurred')
except ValueError:
print('Division by zero error')
except ZeroDivisionError:
print("unexpected error")
except:
print('unexpected error')
else:
print('No exceptions')
When <try suite> is executed, an exception
occurs, the <except suite> is executed with
name bound if found; otherwise unnamed
except suite is executed.
Finally block:
Finally block can be used just like except block but any code placed inside finally block
must execute, whether the try block raised an exception or not.
try:
#statements that may raise exception
[except:
# handle exception here]
finally:
#statements that will always run
Example:
try:
fh=open(poems.txt , r+)
fh.write(Adding new line)
except:
print(Exception has occurred)
finally:
print(goodbye!!!)
The except block is executed only when
exception has occurred but finally block
will be executed always in the end.
Raising/Forcing an Exception:
Raise keyword can be used to raise/force an exception.
The programmer can force an exception to occur through raise keyword with a custome
message to the exception handling module.
Example:
try:
a=int(input(enter numerator))
b=int(input(enter denominator))
if b==0:
raise ZeroDivisionError(str(a)+/0 not possible)
print(a/b)
except ZeroDivisionError as e:
print(Exception, e)
Raise <exception>(<message>)
It is a predefined built-in exception.
Exception handling.pptxnn                                        h

More Related Content

Similar to Exception handling.pptxnn h (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
43c
43c43c
43c
Sireesh K
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
Exception handling in python and how to handle it
Exception handling in python and how to handle itException handling in python and how to handle it
Exception handling in python and how to handle it
s6901412
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
Exception Handling using Python Libraries
Exception Handling using Python LibrariesException Handling using Python Libraries
Exception Handling using Python Libraries
mmvrm
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
Syed Bahadur Shah
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
Faisaliqbal203156
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
Exception Handling in python programming.pptx
Exception Handling in python programming.pptxException Handling in python programming.pptx
Exception Handling in python programming.pptx
shririshsri
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
Exception handling in python and how to handle it
Exception handling in python and how to handle itException handling in python and how to handle it
Exception handling in python and how to handle it
s6901412
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
Exception Handling using Python Libraries
Exception Handling using Python LibrariesException Handling using Python Libraries
Exception Handling using Python Libraries
mmvrm
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
Syed Bahadur Shah
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
Exception Handling in python programming.pptx
Exception Handling in python programming.pptxException Handling in python programming.pptx
Exception Handling in python programming.pptx
shririshsri
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu

Recently uploaded (20)

urine formation.pptx kidney urine formation
urine formation.pptx kidney urine formationurine formation.pptx kidney urine formation
urine formation.pptx kidney urine formation
Pooja Rani
iatrogenic damages of ortho treatment - sunitha.ppt
iatrogenic damages of ortho treatment - sunitha.pptiatrogenic damages of ortho treatment - sunitha.ppt
iatrogenic damages of ortho treatment - sunitha.ppt
PseudoPocket
Ethics in Clinical Research Regulation including historical perspective for (...
Ethics in Clinical Research Regulation including historical perspective for (...Ethics in Clinical Research Regulation including historical perspective for (...
Ethics in Clinical Research Regulation including historical perspective for (...
Om Mahajan
HCA Guide to Making Complaints and Comments Feb 2024 (1).pdf
HCA Guide to Making Complaints and Comments Feb 2024 (1).pdfHCA Guide to Making Complaints and Comments Feb 2024 (1).pdf
HCA Guide to Making Complaints and Comments Feb 2024 (1).pdf
Henry Tapper
Adulterants screening in Herbal products using Modern Analytical Techniques
Adulterants screening in Herbal products using Modern Analytical TechniquesAdulterants screening in Herbal products using Modern Analytical Techniques
Adulterants screening in Herbal products using Modern Analytical Techniques
28SamruddhiKadam
Regulatory Framework for Drug Import Under the Drugs and Cosmetics Act, 1940 ...
Regulatory Framework for Drug Import Under the Drugs and Cosmetics Act, 1940 ...Regulatory Framework for Drug Import Under the Drugs and Cosmetics Act, 1940 ...
Regulatory Framework for Drug Import Under the Drugs and Cosmetics Act, 1940 ...
Dr.Navaneethakrishnan S
Ranitidine Recall:- Regulatory Response to NDMA Contamination
Ranitidine Recall:- Regulatory Response to NDMA ContaminationRanitidine Recall:- Regulatory Response to NDMA Contamination
Ranitidine Recall:- Regulatory Response to NDMA Contamination
Suyash Jain
Caesarean section, Types, Applications and drawbacks
Caesarean section, Types, Applications and drawbacksCaesarean section, Types, Applications and drawbacks
Caesarean section, Types, Applications and drawbacks
Hteinlynnoo1
Let's Talk About It: Ovarian Cancer (Making Meaning after a Cancer Diagnosis)
Let's Talk About It: Ovarian Cancer (Making Meaning after a Cancer Diagnosis)Let's Talk About It: Ovarian Cancer (Making Meaning after a Cancer Diagnosis)
Let's Talk About It: Ovarian Cancer (Making Meaning after a Cancer Diagnosis)
RheannaRandazzo
diabetes mcq by NAME ANKUSH GOYAL (1).pdf
diabetes mcq by NAME ANKUSH GOYAL (1).pdfdiabetes mcq by NAME ANKUSH GOYAL (1).pdf
diabetes mcq by NAME ANKUSH GOYAL (1).pdf
Dr Ankush goyal
Maximizing Therapeutic Innovations in Bladder Cancer: Expert Strategies for C...
Maximizing Therapeutic Innovations in Bladder Cancer: Expert Strategies for C...Maximizing Therapeutic Innovations in Bladder Cancer: Expert Strategies for C...
Maximizing Therapeutic Innovations in Bladder Cancer: Expert Strategies for C...
PVI, PeerView Institute for Medical Education
Detailed Overview of the Drugs and Cosmetics Act, 1940 & Rules
Detailed Overview of the Drugs and Cosmetics Act, 1940 & RulesDetailed Overview of the Drugs and Cosmetics Act, 1940 & Rules
Detailed Overview of the Drugs and Cosmetics Act, 1940 & Rules
Dr.Navaneethakrishnan S
Good Automated Laboratory Practices (GALP) Standards, Compliance, and Impleme...
Good Automated Laboratory Practices (GALP) Standards, Compliance, and Impleme...Good Automated Laboratory Practices (GALP) Standards, Compliance, and Impleme...
Good Automated Laboratory Practices (GALP) Standards, Compliance, and Impleme...
Dr. Smita Kumbhar
Drug_Design PRESENTSTION B.pharm 6th sem. IGNTU AMARKANTAK M.P.
Drug_Design PRESENTSTION B.pharm 6th sem.  IGNTU AMARKANTAK M.P.Drug_Design PRESENTSTION B.pharm 6th sem.  IGNTU AMARKANTAK M.P.
Drug_Design PRESENTSTION B.pharm 6th sem. IGNTU AMARKANTAK M.P.
IGNTU AMARKANTAK (M.P.)
Quality management system regulation (QMSR )Final rule 2024
Quality management system regulation (QMSR )Final rule 2024Quality management system regulation (QMSR )Final rule 2024
Quality management system regulation (QMSR )Final rule 2024
vishwas16691
A New Era in Treating Advanced Ovarian Cancer: Practical Tips for Maximizing ...
A New Era in Treating Advanced Ovarian Cancer: Practical Tips for Maximizing ...A New Era in Treating Advanced Ovarian Cancer: Practical Tips for Maximizing ...
A New Era in Treating Advanced Ovarian Cancer: Practical Tips for Maximizing ...
PVI, PeerView Institute for Medical Education
PROFESSIONAL Integrity, Honesty and Responsibility ppt (1).pdf
PROFESSIONAL Integrity, Honesty and Responsibility ppt (1).pdfPROFESSIONAL Integrity, Honesty and Responsibility ppt (1).pdf
PROFESSIONAL Integrity, Honesty and Responsibility ppt (1).pdf
BhumikaSingh805349
Personal Protection equipments. (G).pptx
Personal Protection equipments. (G).pptxPersonal Protection equipments. (G).pptx
Personal Protection equipments. (G).pptx
GarimaSingh204707
Nervous System (Neurons and Neuroglia).pptx
Nervous System (Neurons and Neuroglia).pptxNervous System (Neurons and Neuroglia).pptx
Nervous System (Neurons and Neuroglia).pptx
PranaliChandurkar2
PLAN EVALUATION HEAD AND NECK CANCER RADIOTHERAPY BY DR KANHU CHARAN PATRO
PLAN EVALUATION HEAD AND NECK CANCER RADIOTHERAPY BY DR KANHU CHARAN PATROPLAN EVALUATION HEAD AND NECK CANCER RADIOTHERAPY BY DR KANHU CHARAN PATRO
PLAN EVALUATION HEAD AND NECK CANCER RADIOTHERAPY BY DR KANHU CHARAN PATRO
Kanhu Charan
urine formation.pptx kidney urine formation
urine formation.pptx kidney urine formationurine formation.pptx kidney urine formation
urine formation.pptx kidney urine formation
Pooja Rani
iatrogenic damages of ortho treatment - sunitha.ppt
iatrogenic damages of ortho treatment - sunitha.pptiatrogenic damages of ortho treatment - sunitha.ppt
iatrogenic damages of ortho treatment - sunitha.ppt
PseudoPocket
Ethics in Clinical Research Regulation including historical perspective for (...
Ethics in Clinical Research Regulation including historical perspective for (...Ethics in Clinical Research Regulation including historical perspective for (...
Ethics in Clinical Research Regulation including historical perspective for (...
Om Mahajan
HCA Guide to Making Complaints and Comments Feb 2024 (1).pdf
HCA Guide to Making Complaints and Comments Feb 2024 (1).pdfHCA Guide to Making Complaints and Comments Feb 2024 (1).pdf
HCA Guide to Making Complaints and Comments Feb 2024 (1).pdf
Henry Tapper
Adulterants screening in Herbal products using Modern Analytical Techniques
Adulterants screening in Herbal products using Modern Analytical TechniquesAdulterants screening in Herbal products using Modern Analytical Techniques
Adulterants screening in Herbal products using Modern Analytical Techniques
28SamruddhiKadam
Regulatory Framework for Drug Import Under the Drugs and Cosmetics Act, 1940 ...
Regulatory Framework for Drug Import Under the Drugs and Cosmetics Act, 1940 ...Regulatory Framework for Drug Import Under the Drugs and Cosmetics Act, 1940 ...
Regulatory Framework for Drug Import Under the Drugs and Cosmetics Act, 1940 ...
Dr.Navaneethakrishnan S
Ranitidine Recall:- Regulatory Response to NDMA Contamination
Ranitidine Recall:- Regulatory Response to NDMA ContaminationRanitidine Recall:- Regulatory Response to NDMA Contamination
Ranitidine Recall:- Regulatory Response to NDMA Contamination
Suyash Jain
Caesarean section, Types, Applications and drawbacks
Caesarean section, Types, Applications and drawbacksCaesarean section, Types, Applications and drawbacks
Caesarean section, Types, Applications and drawbacks
Hteinlynnoo1
Let's Talk About It: Ovarian Cancer (Making Meaning after a Cancer Diagnosis)
Let's Talk About It: Ovarian Cancer (Making Meaning after a Cancer Diagnosis)Let's Talk About It: Ovarian Cancer (Making Meaning after a Cancer Diagnosis)
Let's Talk About It: Ovarian Cancer (Making Meaning after a Cancer Diagnosis)
RheannaRandazzo
diabetes mcq by NAME ANKUSH GOYAL (1).pdf
diabetes mcq by NAME ANKUSH GOYAL (1).pdfdiabetes mcq by NAME ANKUSH GOYAL (1).pdf
diabetes mcq by NAME ANKUSH GOYAL (1).pdf
Dr Ankush goyal
Detailed Overview of the Drugs and Cosmetics Act, 1940 & Rules
Detailed Overview of the Drugs and Cosmetics Act, 1940 & RulesDetailed Overview of the Drugs and Cosmetics Act, 1940 & Rules
Detailed Overview of the Drugs and Cosmetics Act, 1940 & Rules
Dr.Navaneethakrishnan S
Good Automated Laboratory Practices (GALP) Standards, Compliance, and Impleme...
Good Automated Laboratory Practices (GALP) Standards, Compliance, and Impleme...Good Automated Laboratory Practices (GALP) Standards, Compliance, and Impleme...
Good Automated Laboratory Practices (GALP) Standards, Compliance, and Impleme...
Dr. Smita Kumbhar
Drug_Design PRESENTSTION B.pharm 6th sem. IGNTU AMARKANTAK M.P.
Drug_Design PRESENTSTION B.pharm 6th sem.  IGNTU AMARKANTAK M.P.Drug_Design PRESENTSTION B.pharm 6th sem.  IGNTU AMARKANTAK M.P.
Drug_Design PRESENTSTION B.pharm 6th sem. IGNTU AMARKANTAK M.P.
IGNTU AMARKANTAK (M.P.)
Quality management system regulation (QMSR )Final rule 2024
Quality management system regulation (QMSR )Final rule 2024Quality management system regulation (QMSR )Final rule 2024
Quality management system regulation (QMSR )Final rule 2024
vishwas16691
PROFESSIONAL Integrity, Honesty and Responsibility ppt (1).pdf
PROFESSIONAL Integrity, Honesty and Responsibility ppt (1).pdfPROFESSIONAL Integrity, Honesty and Responsibility ppt (1).pdf
PROFESSIONAL Integrity, Honesty and Responsibility ppt (1).pdf
BhumikaSingh805349
Personal Protection equipments. (G).pptx
Personal Protection equipments. (G).pptxPersonal Protection equipments. (G).pptx
Personal Protection equipments. (G).pptx
GarimaSingh204707
Nervous System (Neurons and Neuroglia).pptx
Nervous System (Neurons and Neuroglia).pptxNervous System (Neurons and Neuroglia).pptx
Nervous System (Neurons and Neuroglia).pptx
PranaliChandurkar2
PLAN EVALUATION HEAD AND NECK CANCER RADIOTHERAPY BY DR KANHU CHARAN PATRO
PLAN EVALUATION HEAD AND NECK CANCER RADIOTHERAPY BY DR KANHU CHARAN PATROPLAN EVALUATION HEAD AND NECK CANCER RADIOTHERAPY BY DR KANHU CHARAN PATRO
PLAN EVALUATION HEAD AND NECK CANCER RADIOTHERAPY BY DR KANHU CHARAN PATRO
Kanhu Charan

Exception handling.pptxnn h

  • 2. What is Exception? Advantages of Exception Handling: Unexpected situation or errors occur during the program execution is known as Exception. This will lead to the termination of program execution. For this programmer have no control on. Egs. ATM machine running out of cash, When you try to open a file that does not exit in that path. These type of anomalous situations are generally called exceptions and the way to handle them is called exception handling. Exception handling separates error handling code from normal code It enhances readability It stimulates the error handling to take place one at a time in one manner. It makes for clear, robust, fault tolerant programs.
  • 3. Some common examples of Exception disturb normal flow of execution during run time. Divide by zero errors Accessing th elements of an array/list beyond its range Index Error Invalid input Hard disk crash Opening of non-existing file Heap memory exhausted Example: >>>3/0 Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 3/0 ZeroDivisionError: division by zero This is generated by default exception handler of python. (i) Print out exception description (ii) Prints the stack trace (where the exception occurred (iii) Causes the program termination.
  • 4. Example: >>>l1=[1,2,3] Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> l1[4] IndexError: list index out of range Example: >>>l1=[1,2,3] >>>li[4] Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> li[4] NameError: name 'li' is not defined. Did you mean: 'l1'?
  • 5. Concept of Exception handling: 1. Write a code in such a way that it raises some error flag every time something goes wrong 2. Then trap this error flag and if this is spotted, call the error handling routine. Raising an imaginary error flag is called throwing or raising an error When error is thrown, the overall system responds by catching the error. The surrounding a block of error-sensitive-code-with-exception-handling is called trying to execute a block. Write code such that it raises an error-flag every time something goes wrong ------------------------------- Throw exception If error flag Is raised then Call the error handling routine ------------------------------- Catch exception
  • 6. Description Python terminology An unexpected error that occurs during runtime Exception A set of code that might have an exception thrown in it Try block The process by which an exception is generated and executing atatements that try to resolve the problem Catching The block of code that attempts to deal with the exception (ie. Problem) Except clause for except/exception block or catch block The sequence of method calls that brought control to the point where the exception occurred Stack trace Terminology used with exception handling:
  • 7. When to use Exception Handling: Processing exception situation Processing exception for components that cannot handle them directly Large projects that require uniform error-processing. The segment of code where there is any possibility of error or exception, is placed inside one block. The code to be executed in case the exception has occurred, is placed inside another block. Syntax of Exception Handling: try: #write here the code that may generate an exception except: #write code here about what to do when the exception has occurred
  • 8. Example: try: a,b=int(input("enter a no")),int(input("enter a divisor")) print(a/b) except: print("Division by Zero ! denominator must not be zero") Output 1: enter a no6 enter a divisor3 result of a/b 2.0 Output2: enter a no6 enter a divisor0 Division by Zero ! denominator must not be zero
  • 10. Program to handle exception while opening a file try: myf=open("d:/myf.txt",'r') print(myf.read()) except: print("Error opening a file") OUTPUT: Hello python The above output is displayed if the file has been opened for reading successfully. Otherwise it shows Error opening a file
  • 11. Exception raised because of TypeError and ValueError: import traceback try: a=5 b=int(input("enter a no.")) print(a+b) print(a+"five") except ValueError: print("arithmetic is not possible between a no. and string") except TypeError: print("cannot convert a string to a number")
  • 12. Second argument of the except block: try: # code Except <ExceptionName> as <exArgument>: # handle error file try: print("result of 5/0=",5/5) print("result of 5/0=",5/0) except ZeroDivisionError as e: print("Exception raised",e) Output: result of 5/0= 1.0 Exception raised division by zero
  • 13. Handling multiple errors: Multiple exception blocks one for each exception raised. This will give exact error message for a specific exception than having one common error message for all exception. try: #: except <exceptionName1>: #: except <exceptionName1>: #: except : #: else: #if there is no exception then the statements in this block get executed.
  • 14. Example: try: my_file=open('d:myf.txt') my_line=my_file.readline() my_int=int(s.strip()) my_calc=101/my_int print(my_calc) except IOError: print('I/O error occurred') except ValueError: print('Division by zero error') except ZeroDivisionError: print("unexpected error") except: print('unexpected error') else: print('No exceptions') When <try suite> is executed, an exception occurs, the <except suite> is executed with name bound if found; otherwise unnamed except suite is executed.
  • 15. Finally block: Finally block can be used just like except block but any code placed inside finally block must execute, whether the try block raised an exception or not. try: #statements that may raise exception [except: # handle exception here] finally: #statements that will always run Example: try: fh=open(poems.txt , r+) fh.write(Adding new line) except: print(Exception has occurred) finally: print(goodbye!!!) The except block is executed only when exception has occurred but finally block will be executed always in the end.
  • 16. Raising/Forcing an Exception: Raise keyword can be used to raise/force an exception. The programmer can force an exception to occur through raise keyword with a custome message to the exception handling module. Example: try: a=int(input(enter numerator)) b=int(input(enter denominator)) if b==0: raise ZeroDivisionError(str(a)+/0 not possible) print(a/b) except ZeroDivisionError as e: print(Exception, e) Raise <exception>(<message>) It is a predefined built-in exception.