在处理同一个异常时,如何保护程序不受另一个异常的影响?

2024-10-03 04:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

try:
    grossCheck = int(input("How much? (figures only pls.)\n"))
except ValueError:
    grossCheck = int(input("How much? (FIGURES ONLY PLS.)\n"))

tenPees = grossCheck * 0.1
realPees = grossCheck - tenPees

print("you've got " + str(realPees))

我得到了:

ValueError: invalid literal for int() with base 10: 'w'

During handling of the above exception, another exception occurred:

问题是我之前处理过同样的异常。 我试图处理它的情况下,用户仍然输入错误的值(s)多次没有打破程序。你知道吗


Tags: onlyinputexceptionhowinttryvalueerrorexcept
2条回答

您需要以某种方式处理异常。一种方法是不断地问:

try: 
    grossCheck = int(input("How much? (figures only pls.)\n")) 
except ValueError: 
    while True:
        try: 
            grossCheck = int(input("How much? (FIGURES ONLY PLS.)\n"))
            break
        except ValueError:
            pass
while 1:
    try:
        grossCheck = int(input("How much? (figures only pls.)\n"))
        tenPees = grossCheck * 0.1
        realPees = grossCheck - tenPees

        print("you've got " + str(realPees))
    except ValueError:
        print('You must enter number')

这是处理错误的正确方法之一。 你得到的错误,是因为你把输入除了块,你不应该这样做,在除块你应该打印错误,如果你想,或只是重复尝试块

相关问题 更多 >