首页 > 解决方案 > 如何在用户输入负数时添加异常

问题描述

我正在尝试添加一个例外以识别何时有人输入负数,并回复说您只能输入正数

print('How many cats do you have?')
numCats = input()
try: 
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError: 
    print('You did not enter a number.')

目前它将响应用户输入字符串而不是整数,但我希望它能够通过打印“您不能使用负数”来响应用户输入 -4 之类的内容。

对 Python 来说是全新的,所以任何关于如何添加它的建议都将非常感激,谢谢。

标签: pythonexceptionexcept

解决方案


定义您自己的异常类,您可以选择是否捕获它:

class NegativeNumberException(Exception):
    pass

print('How many cats do you have?')
try:
    numCats = int(input())
    if numCats >=4:
        print('Thats a lot of cats.')
    elif numCats < 0:
        raise NegativeNumberException()
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')
except NegativeNumberException as e:
    print("You entered a negative number.")

推荐阅读