如何使用 sys excepthook,然后在错误消息后从循环中继续执行代码?

How can I use a sys excepthook and then continue the code from a loop after the error message?

我正在尝试创建一个平均求解器,它可以采用元组并对数字进行平均。我想使用 except 钩子给出错误信息,然后从 while 循环的开头继续。 'continue' 不起作用。

import sys
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z==1 :
    def my_except_hook(exctype, value, traceback):
        print('Please only use integers.')
        continue
    sys.excepthook = my_except_hook
    print("Enter your set with commas between numbers.")
    x=input()
    i=len(x)
    print('The number of numbers is:',i)
    y=float(float(sum(x))/i)
    print('Your average is', float(y))
    print(' ')
    print("Would you like to quit? Press 0 to quit, press 1 to continue.")
    z=input()
print('Thank you for your time.')

正如@PatrickHaugh 指出的那样,关键字 continuemy_except_hook 没有任何意义。它仅在 while 循环内相关。我知道这是你试图通过在循环的 flow 中调用 continue 来做的,但它实际上并不在 context 的一个循环,所以它不起作用。


另外,i是你有多少个数字,你却把它设置为用户输入的长度。但是,这将包括逗号!如果您想要 真实 个数字,请设置 i = len (x.split (","))。这将找出逗号之间有多少个数字。

没关系,我解决了问题。我刚刚使用了 try-except 子句...

z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')

while z == 1:
    try:
        print("Enter your set with commas between numbers.")
        x = input()
        i = len(x)
        y = float(float(sum(x)) / i)
        print('Your average is', float(y))
        print(' ')
        print("Would you like to quit? Press 0 to quit, press 1 to continue.")
        z = input()
    except:
        print('Please use integers.')
        x = []
        continue


print('Thank you for your time.')