SlideShare a Scribd company logo
1 of 23
Exception Handling in Python
Dr.G.Jasmine Beulah
Assistant Professor, Dept.Computer Science,
Kristu Jayanti College,Bengaluru
What is an Exception?
• An exception in Python is an incident that happens while
executing a program that causes the regular course of the
program's commands to be disrupted.
• When a Python code comes across a condition it can't handle, it
raises an exception. An object in Python that describes an error
is called an exception.
• When a Python code throws an exception, it has two options:
handle the exception immediately or stop and quit.
# Python code to catch an exception and han
dle it using try and except code blocks
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that
goes beyond the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed
by the Python interpreter
except:
print ("Index out of range")
How to Raise an Exception
• If a condition does not meet our criteria but is correct according
to the Python interpreter, we can intentionally raise an exception
using the raise keyword. We can use a customized exception in
conjunction with the statement.
• If we wish to use raise to generate an exception when a given
condition happens, we may do so as follows:
#Python code to show how to raise an except
ion in Python
num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or e
qual to 3 but is {len(num)}" )
Assertions in Python
• Assertions are commonly used at the beginning of a function to
inspect for valid input and at the end of calling the function to
inspect for valid output.
The assert Statement
• Python examines the adjacent expression, preferably true when
it finds an assert statement. Python throws an AssertionError
exception if the result of the expression is false.
• The syntax for the assert clause is −
assert Expressions[, Argument]
Python uses ArgumentException, if the assertion fails, as the
argument for the AssertionError.
We can use the try-except clause to catch and handle
AssertionError exceptions, but if they aren't, the program will
stop, and the Python interpreter will generate a traceback.
#Python program to show how to use assert key
word
# defining a function
def square_root( Number ):
assert ( Number < 0), "Give a positive integer"
return Number**(1/2)
#Calling function and passing the values
print( square_root( 36 ) )
print( square_root( -36 ) )
What is Assertion?
• Assertions are statements that assert or state a
fact confidently in your program. For example,
while writing a division function, you're confident
the divisor shouldn't be zero, you assert divisor is
not equal to zero.
• Assertions are simply boolean expressions that
check if the conditions return true or not. If it is
true, the program does nothing and moves to the
next line of code. However, if it's false, the
program stops and throws an error.
• It is also a debugging tool as it halts the program
as soon as an error occurs and displays it.
Python assert Statement
• Python has built-in assert statement
to use assertion condition in the
program. assert statement has a
condition or expression which is
supposed to be always true.
• If the condition is false assert halts
the program and gives an
AssertionError.
Syntax for using Assert in Pyhton:
assert <condition>
assert <condition>,<error message>
In Python we can use assert statement
in two ways as follows:
1.assert statement has a condition and
if the condition is not satisfied the
program will stop and give
AssertionError.
2.assert statement can also have a
condition and a optional error message.
If the condition is not satisfied assert
stops the program and gives
AssertionError along with the error
message.
Example: assert
x = 10
assert x > 0
print('x is a positive number.')
Example 1: Using assert without Error Message
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Average of mark1:",avg(mark1))
Example 2: Using assert with error message
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
Key Points to Remember
• Assertions are the condition or boolean expression which are always
supposed to be true in the code.
• assert statement takes an expression and optional message.
• assert statement is used to check types, values of argument and the
output of the function.
• assert statement is used as debugging tool as it halts the program at
the point where an error occurs.
Try with Else Clause
• Python also supports the else clause, which should come after
every except clause, in the try, and except blocks.
• Only when the try clause fails to throw an exception the Python
interpreter goes on to the else block.
# Python program to show how to use else cl
ause with try and except clauses
# Defining a function which returns reciprocal of a number
def reciprocal( num1 ):
try:
reci = 1 / num1
except ZeroDivisionError:
print( "We cannot divide by zero" )
else:
print ( reci )
# Calling the function and passing values
reciprocal( 4 )
reciprocal( 0 )
Finally Keyword in Python
• The finally keyword is available in Python, and it is always used
after the try-except block.
• The finally code block is always executed after the try block has
terminated normally or after the try block has terminated for
some other reason.
# Python code to show the use of finally claus
e
# Raising an exception in try block
try:
div = 4 // 0
print( div )
# this block will handle the exception raised
except ZeroDivisionError:
print( "Atepting to divide by zero" )
# this will always be executed no matter exception is raised or not
finally:
print( 'This is code of finally clause' )
User-Defined Exceptions
class EmptyError( RuntimeError ):
def __init__(self, argument):
self.arguments = argument
Once the preceding class has been created, the following is how to rai
se an
exception:
Code
var = " "
try:
raise EmptyError( "The variable is empty" )
except (EmptyError, var):
print( var.arguments )
Thank You

More Related Content

What's hot (20)

Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Algorithm and c language
Algorithm and c languageAlgorithm and c language
Algorithm and c language
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Functions in python
Functions in python Functions in python
Functions in python
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
String in java
String in javaString in java
String in java
 
Strings in C
Strings in CStrings in C
Strings in C
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Python functions
Python functionsPython functions
Python functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
 
Python data type
Python data typePython data type
Python data type
 

Similar to Exception Handling in Python

Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxPavan326406
 
Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementAbhishekGupta692777
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
Exception handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptxException handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptxshikhaverma566116
 
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.pptRaja Ram Dutta
 
This is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxThis is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxelezearrepil1
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Errors and exception
Errors and exceptionErrors and exception
Errors and exceptionRishav Upreti
 

Similar to Exception Handling in Python (20)

Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
ch-3-exception-handling.pdf
ch-3-exception-handling.pdfch-3-exception-handling.pdf
ch-3-exception-handling.pdf
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_Statement
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
ACP - Week - 9.pptx
ACP - Week - 9.pptxACP - Week - 9.pptx
ACP - Week - 9.pptx
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Exception handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptxException handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptx
 
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
 
This is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxThis is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptx
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Py-Slides-9.ppt
Py-Slides-9.pptPy-Slides-9.ppt
Py-Slides-9.ppt
 
F6dc1 session6 c++
F6dc1 session6 c++F6dc1 session6 c++
F6dc1 session6 c++
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 
Errors and exception
Errors and exceptionErrors and exception
Errors and exception
 

More from DrJasmineBeulahG

More from DrJasmineBeulahG (9)

File Handling in C.pptx
File Handling in C.pptxFile Handling in C.pptx
File Handling in C.pptx
 
Constants and Unformatted Input Output Functions.pptx
Constants and Unformatted Input Output Functions.pptxConstants and Unformatted Input Output Functions.pptx
Constants and Unformatted Input Output Functions.pptx
 
Software Testing.pptx
Software Testing.pptxSoftware Testing.pptx
Software Testing.pptx
 
Software Process Model.ppt
Software Process Model.pptSoftware Process Model.ppt
Software Process Model.ppt
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
STUDENT DETAILS DATABASE.pptx
STUDENT DETAILS DATABASE.pptxSTUDENT DETAILS DATABASE.pptx
STUDENT DETAILS DATABASE.pptx
 
Selection Sort.pptx
Selection Sort.pptxSelection Sort.pptx
Selection Sort.pptx
 
Structures
StructuresStructures
Structures
 
Arrays
ArraysArrays
Arrays
 

Recently uploaded

MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...Krashi Coaching
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/siemaillard
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Denish Jangid
 
Benefits and Challenges of OER by Shweta Babel.pptx
Benefits and Challenges of OER by Shweta Babel.pptxBenefits and Challenges of OER by Shweta Babel.pptx
Benefits and Challenges of OER by Shweta Babel.pptxsbabel
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...Gary Wood
 
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIII BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIagpharmacy11
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17Celine George
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryCeline George
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjMohammed Sikander
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽中 央社
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
 
Benefits and Challenges of OER by Shweta Babel.pptx
Benefits and Challenges of OER by Shweta Babel.pptxBenefits and Challenges of OER by Shweta Babel.pptx
Benefits and Challenges of OER by Shweta Babel.pptx
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIII BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 Inventory
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 

Exception Handling in Python

  • 1. Exception Handling in Python Dr.G.Jasmine Beulah Assistant Professor, Dept.Computer Science, Kristu Jayanti College,Bengaluru
  • 2. What is an Exception? • An exception in Python is an incident that happens while executing a program that causes the regular course of the program's commands to be disrupted. • When a Python code comes across a condition it can't handle, it raises an exception. An object in Python that describes an error is called an exception. • When a Python code throws an exception, it has two options: handle the exception immediately or stop and quit.
  • 3. # Python code to catch an exception and han dle it using try and except code blocks a = ["Python", "Exceptions", "try and except"] try: #looping through the elements of the array a, choosing a range that goes beyond the length of the array for i in range( 4 ): print( "The index and element from the array is", i, a[i] ) #if an error occurs in the try block, then except block will be executed by the Python interpreter except: print ("Index out of range")
  • 4.
  • 5. How to Raise an Exception • If a condition does not meet our criteria but is correct according to the Python interpreter, we can intentionally raise an exception using the raise keyword. We can use a customized exception in conjunction with the statement. • If we wish to use raise to generate an exception when a given condition happens, we may do so as follows:
  • 6. #Python code to show how to raise an except ion in Python num = [3, 4, 5, 7] if len(num) > 3: raise Exception( f"Length of the given list must be less than or e qual to 3 but is {len(num)}" )
  • 7. Assertions in Python • Assertions are commonly used at the beginning of a function to inspect for valid input and at the end of calling the function to inspect for valid output.
  • 8. The assert Statement • Python examines the adjacent expression, preferably true when it finds an assert statement. Python throws an AssertionError exception if the result of the expression is false. • The syntax for the assert clause is − assert Expressions[, Argument] Python uses ArgumentException, if the assertion fails, as the argument for the AssertionError. We can use the try-except clause to catch and handle AssertionError exceptions, but if they aren't, the program will stop, and the Python interpreter will generate a traceback.
  • 9. #Python program to show how to use assert key word # defining a function def square_root( Number ): assert ( Number < 0), "Give a positive integer" return Number**(1/2) #Calling function and passing the values print( square_root( 36 ) ) print( square_root( -36 ) )
  • 10. What is Assertion? • Assertions are statements that assert or state a fact confidently in your program. For example, while writing a division function, you're confident the divisor shouldn't be zero, you assert divisor is not equal to zero. • Assertions are simply boolean expressions that check if the conditions return true or not. If it is true, the program does nothing and moves to the next line of code. However, if it's false, the program stops and throws an error. • It is also a debugging tool as it halts the program as soon as an error occurs and displays it.
  • 11. Python assert Statement • Python has built-in assert statement to use assertion condition in the program. assert statement has a condition or expression which is supposed to be always true. • If the condition is false assert halts the program and gives an AssertionError. Syntax for using Assert in Pyhton: assert <condition> assert <condition>,<error message> In Python we can use assert statement in two ways as follows: 1.assert statement has a condition and if the condition is not satisfied the program will stop and give AssertionError. 2.assert statement can also have a condition and a optional error message. If the condition is not satisfied assert stops the program and gives AssertionError along with the error message.
  • 12. Example: assert x = 10 assert x > 0 print('x is a positive number.')
  • 13. Example 1: Using assert without Error Message def avg(marks): assert len(marks) != 0 return sum(marks)/len(marks) mark1 = [] print("Average of mark1:",avg(mark1))
  • 14. Example 2: Using assert with error message def avg(marks): assert len(marks) != 0,"List is empty." return sum(marks)/len(marks) mark2 = [55,88,78,90,79] print("Average of mark2:",avg(mark2)) mark1 = [] print("Average of mark1:",avg(mark1))
  • 15. Key Points to Remember • Assertions are the condition or boolean expression which are always supposed to be true in the code. • assert statement takes an expression and optional message. • assert statement is used to check types, values of argument and the output of the function. • assert statement is used as debugging tool as it halts the program at the point where an error occurs.
  • 16. Try with Else Clause • Python also supports the else clause, which should come after every except clause, in the try, and except blocks. • Only when the try clause fails to throw an exception the Python interpreter goes on to the else block.
  • 17. # Python program to show how to use else cl ause with try and except clauses # Defining a function which returns reciprocal of a number def reciprocal( num1 ): try: reci = 1 / num1 except ZeroDivisionError: print( "We cannot divide by zero" ) else: print ( reci ) # Calling the function and passing values reciprocal( 4 ) reciprocal( 0 )
  • 18. Finally Keyword in Python • The finally keyword is available in Python, and it is always used after the try-except block. • The finally code block is always executed after the try block has terminated normally or after the try block has terminated for some other reason.
  • 19. # Python code to show the use of finally claus e # Raising an exception in try block try: div = 4 // 0 print( div ) # this block will handle the exception raised except ZeroDivisionError: print( "Atepting to divide by zero" ) # this will always be executed no matter exception is raised or not finally: print( 'This is code of finally clause' )
  • 20. User-Defined Exceptions class EmptyError( RuntimeError ): def __init__(self, argument): self.arguments = argument Once the preceding class has been created, the following is how to rai se an exception: Code var = " " try: raise EmptyError( "The variable is empty" ) except (EmptyError, var): print( var.arguments )
  • 21.
  • 22.