手动降低python

时间:2015-07-10 15:36:19

标签: python python-2.7

有没有办法在异常命中并退出程序之前降低异常以执行其余的try语句?

while(True):
    try:
        do something 1
        error occurs here
        do something 2
    except error as e:
         if(iteration == 2):
             iteration += 1
             # here I want to go back to do something 2 instead of exit()
         exit()

3 个答案:

答案 0 :(得分:2)

The try statement

  

如果finally存在,则指定'cleanup'处理程序。执行try子句,包括任何except和else子句。如果任何子句中发生异常但未处理,则会临时保存该异常。 finally子句被执行。如果存在已保存的异常,则会在finally子句的末尾重新引发异常。如果finally子句引发另一个异常或执行return或break语句,则丢弃保存的异常:

def f():
    try:
        1/0
    finally:
        return 42

>>> f()
42

答案 1 :(得分:0)

您的代码格式有点偏差。请尝试以下

iteration = 0

while True:
    try:
        print(a) # this will cause an error since a isn't defined
    except Exception as e:
        print(str(e)) # this will tell you what the error is
        iteration += 1
        if iteration <= 2:
            iteration += 1
            print(iteration) # just to check if code works , you can remove later
            # here I want to go back to do something 2 instead of exit()
        else:
            exit()

这将运行代码两次,因此if iteration <= 2会在iteration == 3时退出。

答案 2 :(得分:0)

检查特定异常以查看第一个函数是否导致错误或设置标志:

flag = False
while True:
    try:
        do something 1
        error occurs here
        flag = True
        do something 2
    except error as e:
         if not flag:
            do something 
            exit()
    flag  = False

如果do something 1导致错误,则该标志仍然为False,如果是第二个,则该标志将设置为True。

如果只有第一个可以出错,那么只需在{except>中的do something 2

while True:
    try:
        do something 1
        error occurs here
        do something 2
    except error as e:
            do something 2
            exit()