如何重复尝试除外块 [英] How to repeat try-except block

查看:80
本文介绍了如何重复尝试除外块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python 3.3中有一个try-except块,并且希望它无限期运行。

I have a try-except block in Python 3.3, and I want it to run indefinitely.

try:
    imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))
except ValueError:
    imp = int(input("Please enter a number between 1 and 3:\n> ")

当前,如果用户输入非整数,它将按计划工作,但是如果再次输入,则会再次引发ValueError并崩溃。

Currently, if a user were to enter a non-integer it would work as planned, however if they were to enter it again, it would just raise ValueError again and crash.

解决此问题的最佳方法是什么?

What is the best way to fix this?

推荐答案

将其放入while循环中,并在出现循环时中断您期望的输入。最好使所有代码依赖于 try 中的 imp ,如下所示,或设置默认值的值,以防止 NameError 进一步下降。

Put it inside a while loop and break out when you've got the input you expect. It's probably best to keep all code dependant on imp in the try as below, or set a default value for it to prevent NameError's further down.

while True:
  try:
    imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))

    # ... Do stuff dependant on "imp"

    break # Only triggered if input is valid...
  except ValueError:
    print("Error: Invalid number")

编辑:user2678074提出了一个合理的观点,即这可能会使调试变得困难,因为它可能卡在其中无限循环

EDIT: user2678074 makes the valid point that this could make debugging difficult as it could get stuck in an infinite loop.

我将提出两个建议来解决此问题-首先使用具有定义的重试次数的for循环。其次,将以上内容放置在一个函数中,以使其与其余应用程序逻辑保持独立,并且将错误隔离在该函数的范围之内:

I would make two suggestions to resolve this - firstly use a for loop with a defined number of retries. Secondly, place the above in a function, so it's kept separate from the rest of your application logic and the error is isolated within the scope of that function:

def safeIntegerInput( num_retries = 3 ):
    for attempt_no in range(num_retries):
        try:
            return int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))
        except ValueError as error:
            if attempt_no < (num_retries - 1):
                print("Error: Invalid number")
            else:
                raise error

有了这一点,您就可以在函数调用之外进行try / except,只有在您超过最大重试次数后,才能尝试。

With that in place, you can have a try/except outside of the function call and it'll only through if you go beyond the max number of retries.

这篇关于如何重复尝试除外块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆