python1
python1
PYTHON PRORAMMING(22IT14303)
FLIPPED CLASSROOM ACTIVITY ON
• EXCEPTION HIERARCHY By
• HANDLING MULTIPLE EXCEPTION VISHAL R S
222071110
B.TECH IT B
What is exception python:
01 02 03
An Exception is an Whenever there is It basically prevents
error that happens an error, Python the program from
during the generates an getting crashed.
execution of a exception that
program. could be handled.
EXPECTION HIERACHY IN
PYTHON:
ZERO
ATTRIBUTE ASSERTION LOGICAL
DIVISION
ERROR ERROR ERROR
ERROR
TYPE ERROR:
• It occurs when a function and
operation are applied in an
incorrect type
Sample program: Output:
try:
66
a=int(input())
b=input()
11
Print(a+b) Type error unsupported
except TypeError as m: oprand type(s)for /:'int'
Print("type error",m) and 'str'
VALUE ERROR:
• It occurs when a function and
operation are applied in an
incorrect value
Sample program: Output:
try:
66
a=int(input())
b=int(input())
hi
Print(a+b) Value error invalid literal
except ValueError as a: for int() with base 10:'hi'
Print("value error",a)
INDEX ERROR:
• It occurs when a function and
operation are applied in an
incorrect index
Sample program: Output:
try:
index error list index out
a=[1,2,3,4]
of range
Print(a[4])
except IndexError as a:
Print("index error",a)
NAME ERROR:
• It occurs when a function and
operation are applied in an
incorrect name
Sample program: Output:
try:
Name error name 'c' is
Print(c)
not defined
except NameError as a:
Print("name error",a)
KEY ERROR:
• It occurs when a function and
operation are applied in an
incorrect key
Sample program: Output:
try: Key error 9
c={1:2,3:3,7:9}
Print(c)
except KeyError as a:
Print("key error",a)
HANDLING MULTIPLE EXCEPTION IN PYTHON :
These are where you define the code that will run when
exceptions occur.
N else:
If there is no exception than execute this
block
finally:
Statement in this block must excute
EXCEPTION HANDLING WITH TRY , EXCEPT,ELSE AND
FINALLY :
TRY:
This block will test the excepted error to occur
EXCEPT:
Here you can handle the error
ELSE:
If there is no exception then this block will be
executed
FINALLY:
Finally block always gets executed either
exception is generated or not
Sample program in multiple exception:
try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a valid
number.")
else:
print("there is an no excetion")
finally:
print("process will be completed")
Catching Multiple Exceptions using a List