调用异常后,跳转到python中导致异常的行指令

时间:2014-02-02 14:40:07

标签: python exception exception-handling

有没有办法返回并重复处理Python中异常的指令?

E.g。如果我们通过input()方法获取一些数据,并且由于某种原因导致异常(例如,当尝试将输入字符串转换为int时),我们引发了异常,但在异常之后,我想再次转到input()所在的同一行。

请注意,“continue”不是一个选项,即使它处于循环中,因为它可能是几个不同的输入()将它们分配给循环的不同部分中的不同变量。

所以问题又是:

while 1:
    try:
        foo = int(input(">")
        ...some other code here...
        bar = int(input(">")
        ...some other code here...
        fred = int(input(">")
        ...some other code here...

    except Exception:
        ... do something for error handling and ...
        jump_back_and_repeat_last_line_that_caused_the_exception

想象一下,上面的代码可能在一个循环中,并且异常可能在任何指令中引起(foo ... bar ... fred ...等,甚至可以是任何其他行)。因此,如果它在“bar”行中失败,它应该再次尝试“bar”行。

在python中是否有任何保留字要做?

3 个答案:

答案 0 :(得分:3)

定义一个函数;处理那里的例外情况。

def read_int():
    while 1:
        try:
            value = int(input('>'))
        except ValueError:
            # Error handling + Jump back to input line.
            continue
        else:
            return value

while 1:
    foo = read_int()
    bar = read_int()
    fred = read_int()

答案 1 :(得分:2)

可能有办法做到这一点,但可能会导致设计非常糟糕。

如果我理解正确,那么问题在于调用input引起的异常。

如果情况确实如此,那么您应该在一个单独的方法中实现它,它将正确处理异常:

foo = getUserInput()
...some other code here...
bar = getUserInput()
...some other code here...
fred = getUserInput()
...some other code here...

def getUserInput():
    while 1:
        try:
            return int(input(">"))
        except Exception:
            pass

答案 2 :(得分:1)

except中不做任何事情:

while 1:
    try:
        a=int(raw_input('input an integer: ')) #on python2 it's "raw_input" instead of "input"
        break
    except ValueError, err:
        # print err
        pass
print 'user input is:', a

输出是:

D:\U\ZJ\Desktop> py a.py
input an integer: a
input an integer: b
input an integer: c
input an integer: 123
user input is: 123
相关问题