User Defined Exception handling in Python programming handling provides a way to transfer control from one part of a program to another. In the following programs you will learn that how to define specific exception to except.
while True: #executing Loop.
try: #trying to execute the program.
x = int(input("Please Enter a Number: ")) #if user enter correct
print("Entered value is correct")
break #than Break the process, if not than
except ValueError: #catching Exception and printing.
print("Oops! That was no Valid Number. Try Again...")
x = 5
y = 0
try: #trying to execute.
z = x / y #dividing and assigning to 'z' if equal to Zero then
print("This Will Not Printing")
except ZeroDivisionError: #catch Error and
print("divide by zero") #print this.
#U also Use Base Exception like 'except BaseException:'
#and Exception like 'except Exception:'
x = 5
y = 0
try: #trying to execute.
z = x / y #dividing and assigning to 'z' if equal to Zero then
print("This Will Not Printing")
except ZeroDivisionError: #catch Error and
print("divide by zero") #print this.
finally: #finally Must Executing.
print("This is Must Printing.")
x = 5
y = 1
try: #trying to execute.
z = x / y #deviding and assigning to 'z' if equal to Zero then
print("This Will Printing")
except ZeroDivisionError: #catch Error and
print("This Will Not Printing") #print this.
else: #if not then
print("Not Divide by Zero, and This is Also Printing") #print this.
x = 5
y = 1
try: #trying to execute.
z = x / y #deviding and assigning to 'z' if equal to Zero then
print("This Will Printing")
except ZeroDivisionError: #catch Error and
print("This Will Not Printing") #print this.
else: #if not then
print("Not Divide by Zero, and This is Also Printing") #print this.
finally: #finally Must Executing.
print("This is Must Printing.")