User Defined Exception in Python

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.

Program User Defined Exception

Program

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...")
Output
Please Enter a Number: abc
Oops! That was no Valid Number. Try Again...
Please Enter a Number: admin
Oops! That was no Valid Number. Try Again...
Please Enter a Number: 232
Entered value is correct

Program Working with User Defined Exception

Program

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:'
Output
divide by zero

Program User Defined Exception using Try and Finally

Program

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.")
Output
divide by zero
This is Must Printing.

Program User Defined Exception using Try and Else
Program

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.
Output
This Will Printing
Not Divide by Zero, and This is Also Printing

Program User Defined Exception using Try and Else and Finally
Program

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.")
Output
This Will Printing
Not Divide by Zero, and This is Also Printing
This is Must Printing.