try-except-finally Block
☞ The finally block is always executed irrespective of whether an exception has occurred in a try block or not.
☞ 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
finally:
#Always get executed
☞ 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")
finally:
print("Thank you!!!")
☞ Output :
Enter first number : 5
Enter second number : 0
Sorry!! you have done something wrong
Thank you!!!