【问题标题】:how do i safeguard my program from another exception while handling the same one?在处理同一个异常时,如何保护我的程序免受另一个异常的影响?
【发布时间】:2017-07-26 07:40:46
【问题描述】:
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:

问题是我之前刚刚处理过同样的异常。 我正在尝试处理它,以防用户仍然多次输入错误的值而不破坏程序。

【问题讨论】:

  • 你需要展示你的代码,以及完整的回溯。给定数据不足。

标签: python python-3.x exception-handling


【解决方案1】:

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

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

【讨论】:

  • 为什么要在 try 和 catch 块中重复代码,检查我的答案以了解更好的错误处理方式
  • 我重复一遍,因为 OP 重复了,我复制了他的功能,但修复了他所询问的错误。另请注意,他在input 中有不同的字符串。
  • 没关系,你可以随意改变字符串,但是while循环不应该在除了块里面,如果你有5个错误例外而不是ValueError,你需要有,在每个例外中,每个错误还有五个例外
  • 说得好(也许你需要被告知这一点)我回答了他的问题,没有别的。 SO 不是代码编写服务。你这样做的方式可能更好,但它不能回答他的问题。
  • 我不想和你们争论,我只是给你们两个建议,代码应该如何编写,我的代码确实回答了他的问题,因为它可以正确处理错误
【解决方案2】:
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')

这是处理错误的正确方法之一。 你得到的错误,是因为你已经在 except 块中输入了输入,你不应该这样做,在 except 块中你应该打印错误,如果你愿意,或者只是重复 try 块

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 2023-04-03
    • 2019-11-12
    • 1970-01-01
    • 2021-02-04
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多