Proper way to declare custom exceptions in modern Python?

后端 未结 11 1934
栀梦
栀梦 2020-11-22 08:04

What\'s the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instan

11条回答
  •  星月不相逢
    2020-11-22 08:20

    Try this Example

    class InvalidInputError(Exception):
        def __init__(self, msg):
            self.msg = msg
        def __str__(self):
            return repr(self.msg)
    
    inp = int(input("Enter a number between 1 to 10:"))
    try:
        if type(inp) != int or inp not in list(range(1,11)):
            raise InvalidInputError
    except InvalidInputError:
        print("Invalid input entered")
    

提交回复
热议问题