Handling user defined exceptions in Python

 # we'll define a base class for user-defined exception handling

class Error(Exception):
    """Base class for user-defined exception..."""
    pass

class ValueTooSmallError(Error):
    """Value is smaller than expected"""
    pass

class ValueTooLargeError(Error):
    """Value is larger than expected"""
    pass

num=46

while True:
    try:
        user_input=int(input("Guess the number?:"))
        assert isinstance(user_input, int)

        if user_input<num:
            raise ValueTooSmallError()
        elif user_input>num:
            raise ValueTooLargeError()
        break

    except ValueTooLargeError as e:
        print(e.__doc__,"\n",)
       
    except ValueTooSmallError as e:
        print(e.__doc__,"\n")

    except:
        print("Some error occured! Try again\n")    
 

print("Congo!!! You guessed it correctly.")        

Comments

Popular Posts