How to Create a User Define Exception in Python

Rajani Kushwah
Jun 14, 2021

We can define our own exception derived from the Exception class. Usually, in a module, we define a single base class derived from Exception and derive all the other exception classed from that. An example of this is shown below,

class Error(Exception):
pass

class valueTooLarge(Error):
pass

class valueTooSmall(Error):
pass
def main():

number = 7

try:
input_number = int(input("Enter a number:"))

if input_number > number:
raise valueTooLarge

if input_number < number:
raise valueTooSmall

else:
print("perfect")


except valueTooLarge:
print("Value is too large")

except valueTooSmall:
print("Value is too small")

finally:
print("Exception over")
if __name__ == "__main__":
main()

--

--