SlideShare 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

PPT
Exception Handling on 22nd March 2022.ppt
PPTX
Exception handling with python class 12.pptx
PPTX
Error and exception in python
PPTX
Exceptions overview
PPT
Exception Handling Exception Handling Exception Handling
PPT
Exception
PDF
Ch-1_5.pdf this is java tutorials for all
PPT
Py-Slides-9.ppt
Exception Handling on 22nd March 2022.ppt
Exception handling with python class 12.pptx
Error and exception in python
Exceptions overview
Exception Handling Exception Handling Exception Handling
Exception
Ch-1_5.pdf this is java tutorials for all
Py-Slides-9.ppt

Similar to Exception handling.pptxnn h (20)

PPSX
Exception Handling
PPTX
PPT
Java: Exception
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPTX
Exception Handling,finally,catch,throw,throws,try.pptx
PPT
Exception handling in python and how to handle it
PPTX
UNIT-3.pptx Exception Handling and Multithreading
PPT
Exception Handling using Python Libraries
PPTX
What is Exception Handling?
PPTX
Z blue exception
PPT
Exception handling
PPTX
UNIT III 2021R.pptx
PPTX
UNIT III 2021R.pptx
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Java-Exception Handling Presentation. 2024
PPT
Exception Handling.ppt
PPT
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
DOCX
Exception handling in java
PPTX
Exception Handling in python programming.pptx
PPT
exceptionvdffhhhccvvvv-handling-in-java.ppt
Exception Handling
Java: Exception
unit 4 msbte syallbus for sem 4 2024-2025
Exception Handling,finally,catch,throw,throws,try.pptx
Exception handling in python and how to handle it
UNIT-3.pptx Exception Handling and Multithreading
Exception Handling using Python Libraries
What is Exception Handling?
Z blue exception
Exception handling
UNIT III 2021R.pptx
UNIT III 2021R.pptx
Exception Handling In Java Presentation. 2024
Java-Exception Handling Presentation. 2024
Exception Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Exception handling in java
Exception Handling in python programming.pptx
exceptionvdffhhhccvvvv-handling-in-java.ppt
Ad

Recently uploaded (20)

PPT
Copy-Histopathology Practical by CMDA ESUTH CHAPTER(0) - Copy.ppt
PPT
Obstructive sleep apnea in orthodontics treatment
PPT
ASRH Presentation for students and teachers 2770633.ppt
PPTX
NEET PG 2025 Pharmacology Recall | Real Exam Questions from 3rd August with D...
PDF
NEET PG 2025 | 200 High-Yield Recall Topics Across All Subjects
PPTX
JUVENILE NASOPHARYNGEAL ANGIOFIBROMA.pptx
PPT
MENTAL HEALTH - NOTES.ppt for nursing students
PPTX
15.MENINGITIS AND ENCEPHALITIS-elias.pptx
PPTX
SKIN Anatomy and physiology and associated diseases
PPTX
Gastroschisis- Clinical Overview 18112311
PDF
Deadly Stampede at Yaounde’s Olembe Stadium Forensic.pdf
DOC
Adobe Premiere Pro CC Crack With Serial Key Full Free Download 2025
DOCX
NEET PG 2025 | Pharmacology Recall: 20 High-Yield Questions Simplified
PPTX
Acid Base Disorders educational power point.pptx
PPTX
Electromyography (EMG) in Physiotherapy: Principles, Procedure & Clinical App...
PPTX
Slider: TOC sampling methods for cleaning validation
PPTX
Neuropathic pain.ppt treatment managment
PPT
1b - INTRODUCTION TO EPIDEMIOLOGY (comm med).ppt
PPT
genitourinary-cancers_1.ppt Nursing care of clients with GU cancer
PPTX
Fundamentals of human energy transfer .pptx
Copy-Histopathology Practical by CMDA ESUTH CHAPTER(0) - Copy.ppt
Obstructive sleep apnea in orthodontics treatment
ASRH Presentation for students and teachers 2770633.ppt
NEET PG 2025 Pharmacology Recall | Real Exam Questions from 3rd August with D...
NEET PG 2025 | 200 High-Yield Recall Topics Across All Subjects
JUVENILE NASOPHARYNGEAL ANGIOFIBROMA.pptx
MENTAL HEALTH - NOTES.ppt for nursing students
15.MENINGITIS AND ENCEPHALITIS-elias.pptx
SKIN Anatomy and physiology and associated diseases
Gastroschisis- Clinical Overview 18112311
Deadly Stampede at Yaounde’s Olembe Stadium Forensic.pdf
Adobe Premiere Pro CC Crack With Serial Key Full Free Download 2025
NEET PG 2025 | Pharmacology Recall: 20 High-Yield Questions Simplified
Acid Base Disorders educational power point.pptx
Electromyography (EMG) in Physiotherapy: Principles, Procedure & Clinical App...
Slider: TOC sampling methods for cleaning validation
Neuropathic pain.ppt treatment managment
1b - INTRODUCTION TO EPIDEMIOLOGY (comm med).ppt
genitourinary-cancers_1.ppt Nursing care of clients with GU cancer
Fundamentals of human energy transfer .pptx
Ad

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.