SlideShare a Scribd company logo
9
Most read
17
Most read
19
Most read
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")
Exception Handling in Python
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 )
Exception Handling in Python
Exception Handling in Python
Thank You

More Related Content

PDF
Python functions
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
PDF
Python programming : Exceptions
PPT
File in c
PDF
Python programming : Control statements
PDF
Python functions
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Python programming : Exceptions
File in c
Python programming : Control statements

What's hot (20)

PPTX
The Django Web Application Framework 2
PDF
Python programming : Strings
PPTX
Python in 30 minutes!
PPT
Python Objects
PPT
Python Control structures
PPSX
Programming with Python
PPTX
Introduction to Python programming Language
PPT
Operator Overloading
PDF
Hm system programming class 1
PPTX
Python: Modules and Packages
PPT
File handling in c
PPTX
PHP Presentation
PPTX
Python Exception Handling
PDF
Python Flow Control
PDF
Java Course 8: I/O, Files and Streams
PPTX
Data file handling in c++
PPTX
C Programming: Control Structure
PPTX
Polymorphism in C++
PDF
C++ OOPS Concept
The Django Web Application Framework 2
Python programming : Strings
Python in 30 minutes!
Python Objects
Python Control structures
Programming with Python
Introduction to Python programming Language
Operator Overloading
Hm system programming class 1
Python: Modules and Packages
File handling in c
PHP Presentation
Python Exception Handling
Python Flow Control
Java Course 8: I/O, Files and Streams
Data file handling in c++
C Programming: Control Structure
Polymorphism in C++
C++ OOPS Concept
Ad

Similar to Exception Handling in Python (20)

PDF
Unit 4-Exception Handling in Python.pdf
PPTX
Python Unit II.pptx
PPT
Exception Handling Exception Handling Exception Handling
PDF
ch-3-exception-handling.pdf
PDF
22 scheme OOPs with C++ BCS306B_module5.pdf
PPTX
Exception Handling.pptx
PPTX
Python if_else_loop_Control_Flow_Statement
PPT
Firoze_Errors_Exceptions in python__.ppt
PPT
Firoze_Errors_Exceptions in python__.ppt
DOCX
Exception handlingpdf
PPTX
ACP - Week - 9.pptx
PPT
Java Exception.ppt
PPTX
Exception Handling in Python programming.pptx
PPTX
Exception Handling in Python Programming.pptx
PPT
Exception handling in python and how to handle it
PPTX
Exception handling and throw and throws keyword in java.pptx
PPT
Exception Handling on 22nd March 2022.ppt
PPTX
This is all about control flow in python intruducing the Break and Continue.pptx
ODP
Unit 4-Exception Handling in Python.pdf
Python Unit II.pptx
Exception Handling Exception Handling Exception Handling
ch-3-exception-handling.pdf
22 scheme OOPs with C++ BCS306B_module5.pdf
Exception Handling.pptx
Python if_else_loop_Control_Flow_Statement
Firoze_Errors_Exceptions in python__.ppt
Firoze_Errors_Exceptions in python__.ppt
Exception handlingpdf
ACP - Week - 9.pptx
Java Exception.ppt
Exception Handling in Python programming.pptx
Exception Handling in Python Programming.pptx
Exception handling in python and how to handle it
Exception handling and throw and throws keyword in java.pptx
Exception Handling on 22nd March 2022.ppt
This is all about control flow in python intruducing the Break and Continue.pptx
Ad

More from DrJasmineBeulahG (9)

PPTX
File Handling in C.pptx
PPTX
Constants and Unformatted Input Output Functions.pptx
PPTX
Software Testing.pptx
PPT
Software Process Model.ppt
PPTX
NumPy.pptx
PPTX
STUDENT DETAILS DATABASE.pptx
PPTX
Selection Sort.pptx
PPTX
Structures
PPTX
File Handling in C.pptx
Constants and Unformatted Input Output Functions.pptx
Software Testing.pptx
Software Process Model.ppt
NumPy.pptx
STUDENT DETAILS DATABASE.pptx
Selection Sort.pptx
Structures

Recently uploaded (20)

PPTX
Cell Structure & Organelles in detailed.
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Lesson notes of climatology university.
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Trump Administration's workforce development strategy
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Pharma ospi slides which help in ospi learning
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
Cell Structure & Organelles in detailed.
Weekly quiz Compilation Jan -July 25.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
STATICS OF THE RIGID BODIES Hibbelers.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Chinmaya Tiranga quiz Grand Finale.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Complications of Minimal Access Surgery at WLH
Lesson notes of climatology university.
01-Introduction-to-Information-Management.pdf
Final Presentation General Medicine 03-08-2024.pptx
Trump Administration's workforce development strategy
Abdominal Access Techniques with Prof. Dr. R K Mishra
Pharma ospi slides which help in ospi learning
human mycosis Human fungal infections are called human mycosis..pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Microbial disease of the cardiovascular and lymphatic systems
O5-L3 Freight Transport Ops (International) V1.pdf
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Orientation - ARALprogram of Deped to the Parents.pptx

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")
  • 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 )