try with multiple except Block
☞ The try statement may have multiple except blocks with Exception names to handle specific exceptions and one optional except clause.
☞ Syntax :
try:
#run this code
except Exception_name_1:
#execute this code when there is an exception
except Exception_name_2:
#execute this code when there is an exception
except Exception_name_3:
#execute this code when there is an exception
except :
#execute this code when no match found
☞ Example :
try:
a = int(input("Enter first number : "))
b = int(input("Enter second number : "))
c = a/b
print("Answer = ", c)
except NameError:
print("Wrong variable name")
except ZeroDivisionError:
print("Number cannot be divided by 0")
except:
print("An error has occured")
☞ Output :
Enter first number : 5
Enter second number : 0
Number cannot be divided by 0