强制 try-except 失败的最佳方法(Python)?

乘风 python 194

原文标题Best way to force a try-except to fail (Python)?

我正在编写一个要求用户进行两个输入的代码,然后将使用 try: 检查它们是否都是整数,然后使用 If 语句检查它们是否都高于 0。如果不满足这些条件中的任何一个,则错误“请仅使用正非零整数。”将会呈现。显示此消息的最佳方式是什么,无论它失败的原因是什么,而只需编写该行一次(而不是在 If 语句之后再打印一行)?如果 If 语句为真,我在下面有一行随机文本,这会导致 try: 失败并且代码运行除了:

try:
    runs, increment = int(runs), int(increment)
    if (increment == 0):
        print ("I can't increment in steps of 0.")
    elif (increment < 0 or runs <= 0):
        this line has no meaning, and will make the program go to the except: section
except:
    print('Positive non zero integers only please.')

这可以满足我的要求,但并不是一个很好的解决方案,所以我只是好奇是否有任何其他方法可能有效,或者我应该在 if 语句之后放置相同的打印行吗? (我不能为每个失败单独发送消息,因为这是一个学校项目,所以输出需要与我们得到的完全一致)

原文链接:https://stackoverflow.com//questions/71462291/best-way-to-force-a-try-except-to-fail-python

回复

我来回复
  • Samwise的头像
    Samwise 评论

    你想要的是一个raise语句:

    try:
        runs, increment = int(runs), int(increment)
        if increment < 1 or runs < 1:
            raise ValueError
    except ValueError:
        print("Positive non zero integers only please.")
    

    注意int()会引发ValueError如果它不能将值转换为int,所以except ValueError应该抓住任何一种情况。 (有一个捕捉未知错误的bareexcept:是一个坏习惯,它会使你的代码更难调试;最好尽早打破它!)

    2年前 0条评论