2016-06-28 26 views
0

在我所写的内容中,NoResultException可以在我的try区段或我的except UnexpectedAlertPresentException区段中引发。在这两种情况下,我都想去except NoResultException区块,但只有在try区块中产生NoResultException时才会这样做。这大约是我现在有:处理除外条款中出现的异常

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,但我试图避免重复自己。有没有更好的方法来做到这一点?

+2

通常情况下,您不应该在可能引发更多异常的'except'块内进行操作,但如果必须,您可以将处理分为单独的处理内部异常可能性的函数 –

回答

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

尽量不要过度使用异常处理控制流程。逻辑可能很难推理,而缩进可能变得非常深刻。