处理except子句中引发的异常

时间:2016-06-28 15:59:34

标签: python

在我所写的内容中,NoResultException可以在try块或我的except UnexpectedAlertPresentException块中引发。在任何一种情况下,我都想转到except NoResultException块,但只有在NoResultException块中引发try时才会这样做。这几乎就是我现在所拥有的:

try:
    # do things
except UnexpectedAlertPresentException:
    # do other things, including possibly raise NoResultException
except NoResultException:
    # handle exception

我可以将其更改为:

try:
    # do things
except UnexpectedAlertPresentException:
    try:
        # do other things, including possibly raise NoResultException
    except NoResultException:
        # handle exception
except NoResultException:
    # handle exception

处理NoResultException,但我试图避免重复自己。有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

try:
    try:
        # do things
    except UnexpectedAlertPresentException:
        # do other things, including possibly raise NoResultException
except NoResultException:
    # handle exception

尽量不要过度使用异常处理控制流程。逻辑很难理解,压痕可以变得很深。