Python Exception Handling
Python Exception Handling
Python Exception Handling
Several built-in Python exceptions that can be raised when an error occurs during the
execution of a program.
Example
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
finally:
print("The 'try except' is finished")
Catching Specific Exception
A try statement can have more than one
except clause, to specify handlers for different
exceptions.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Raise an exception
• As a Python developer you can choose to
throw an exception if a condition occurs.
• To throw (or raise) an exception, use
the raise keyword.
Example:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
• The raise statement allows the programmer to
force a specific exception to occur. The sole
argument in raise indicates the exception to
be raised.
Example:
try:
raise NameError("Hi there")
Output:
except NameError: Traceback (most recent call last):
File
print ("An exception") "/home/d6ec14ca595b97bff8d8034bbf
212a9f.py", line 5, in <module>
raise raise NameError("Hi there") # Raise
Error
NameError: Hi there
try:
x = 10
y="xyz"
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block") print("Division by 0 not
accepted")
except:
print('Error occurred.')
else:
print("Division = ", z)
finally:
print("Executing finally block") x=0 y=0 print ("Out of try, except,
else and finally blocks." )
Assertions in Python
• Assertions are mainly assumptions that a
programmer knows or always wants to be true and
hence puts them in code so that failure of these
doesn’t allow the code to execute further.
Parameters:
condition : The boolean condition returning true or false.
error_message : The optional argument to be printed in console
in case of AssertionError
# initializing number
a=4
b=0
Output:
11 print(a / b)
AssertionError:
# Python 3 code to demonstrate
# working of assert
# initializing number
a=4
Output:
b=0 AssertionError: Zero Division Error
mark1 = []
print("Average of mark1:",avg(mark1))
#Python program to show how to use assert keyword
# defining a function
def square_root( Number ):
assert ( Number < 0), "Give a positive integer"
return Number**(1/2)