2016-12-01 60 views
0

我有等同于以下代码:这个异常处理如何更简单?

class SomeError(Exception): pass 

def do_things_with(fileobject): 
    # Do things, and at some point the line below MAY be called 
    raise SomeError 

def try_another_approach(): 
    # Do different things, but at some point the line below MAY be called 
    raise SomeError 

try: 
    try: 
     with open('somefile') as somefile: 
      do_things_with(somefile) 
    except FileNotFoundError: 
     try_another_approach() 
except SomeError: 
    print('Ooops') 

也就是说,我试图打开一个文件(或可能会引发其他一些例外的任何其他东西),如果失败了不同的方法可以使用,但是这两种方法都可能引发同样的例外情况。

现在我有一个嵌套的try /处理这除了,如图所示,但我很乐意做这样的事情:

try: 
    with open('somefile') as somefile: 
     do_things_with(somefile) 
except FileNotFoundError: 
    # I'd like to have any SomeError raised from the function below 
    # at the except clause just below, to keep code compact as I may 
    # be adding more exceptions in the future 
    try_another_approach() 
except SomeError: 
    print('Ooops') 

当然不工作(我得到的一个During handling of the above exception, another exception occurred),但它说明了我想实现的目标:可以处理在try块中以及除块以外的块中的异常,并且不嵌套

我不需要需要为了避免嵌套,我只是好奇的解决这个问题的任何方式,而不必巢,以防万一。

Python中是否有可能?

在此先感谢:)

回答

2

不,你不能。 except子句中引发的异常将在外部块中查找处理程序(即嵌套)。如果不采用嵌套的方式,目前还没有其他方法可以解决这个问题。

删除嵌套的唯一方法是减少异常;也就是,而不是raise Error you return这个值表示出现了问题。在这种情况下,您将根据返回的值(使用if子句)采取行动,而不是根据返回的异常(使用try-except子句)采取行动。

+0

谢谢,@ jim-fasarakis-hilliard,这就是我想象的,但我只是好奇。我很好奇的原因是因为这种模式不断出现在我必须维护的代码中,并不总是可以用'return'来代替。使用嵌套没什么大不了的,但有时候,特别是当你使用'with'子句时,缩进可能会很难看。 –