''' Example from https://www.programiz.com/python-programming/user-defined-exception by Xiannong Meng 2017-07-27 ''' ''' # define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class ValueTooSmallError(Error): """Raised when the input value is too small""" pass class ValueTooLargeError(Error): """Raised when the input value is too large""" pass ''' class ValueTooSmallError(Exception): """Raised when the input value is too small""" #pass def __init__(self): self.__name__ = 'ValueTooSmall' print(self) def __str__(self): return self.__name__ class ValueTooLargeError(Exception): """Raised when the input value is too large""" #pass def __init__(self): self.__name__ = 'ValueTooLarge' print(self) def __str__(self): return self.__name__ # our main program # user guesses a number until he/she gets it right # you need to guess this number number = 10 while True: try: i_num = int(input("Enter a number: ")) if i_num < number: raise ValueTooSmallError elif i_num > number: raise ValueTooLargeError break except ValueTooSmallError: print("This value is too small, try again!") print() except ValueTooLargeError: print("This value is too large, try again!") print() print("Congratulations! You guessed it correctly.")