python - 异常后继续,然后引发它

python - move on after exception and raise it afterwards

我认为这应该有点棘手但在某种程度上是可行的,但我需要帮助。 我想从我的 main() 函数中执行两个函数。 我希望能够分别捕获两者的异常,但仍然能够执行两者并在另一个引发异常时至少获得其中一个的结果。

假设我有:

def foo():
    raise TypeError

def bar():
    return 'bar'

如果我这样做(改编自here):

def multiple_exceptions(flist):
    for f in flist:
        try:
            return f()
        except:
            continue

def main():
    multiple_exceptions([foo, bar])

main()

main() 会 return 'bar',但我还是希望能够从 foo() 中抛出异常。这样,我仍然会得到我的一个函数的结果,而另一个函数中出现错误的信息。

您可以使用'as'捕获和存储异常,例如:

try:
    raise Exception('I am an error!')
    print('The poster messed up error-handling code here.') #should not be displayed
except Exception as Somename:
    print(Somename.message) 
    # you'll see the error message displayed as a normal print result; 
    # you could do print(stuff, file=sys.stderr) to print it like an error without aborting

print('Code here still works, the function did not abort despite the error above')

...or you can do:
except Exception as Somename:
    do_stuff()
    raise Somename

感谢您的评论。 我这样做解决了:

def multiple_exceptions(flist):

    exceptions = []

    for f in flist:
        try:
            f()
        except Exception as  e:
            exceptions.append(e.message)
            continue

    return exceptions

def main():
    multiple_exceptions([foo, bar])

error_messages = main() # list of e.messages occurred (to be raised whenever I want)

然后我可以提出我的异常,例如raise Exception(error_messages[0])(在这种情况下我只关心第一个)。