2013-07-17 87 views
1

我清理了一些代码,并已经运行到的地方有一试重复清除动作/情形除外一把:清理方式来处理python异常?

try: 
    ... 
except KeyError , e : 
    cleanup_a() 
    cleanup_b() 
    cleanup_c() 
    handle_keyerror() 
except ValuesError , e : 
    cleanup_a() 
    cleanup_b() 
    cleanup_c() 
    handle_valueerror() 

我想使这些多一点标准化可读性和维护。在“清理”行动似乎是本地的块,所以它不会是干净多了做以下(尽管它会规范了一点):

def _cleanup_unified(): 
    cleanup_a() 
    cleanup_b() 
    cleanup_c() 
try: 
    ... 
except KeyError , e : 
    _cleanup_unified() 
    handle_keyerror() 

except ValuesError , e : 
    _cleanup_unified() 
    handle_valueerror() 

任何人都可以提出处理这个的替代方法?

+0

我注意到,有一些实际上是回答两个不同的问题非常良好的反应。也许可以添加一些说明你正在寻找什么? – SethMMorton

回答

1

您可以通过捕获所有的人在同一除了和测试类型这样differenciate错误:

try: 
    ... 
except (KeyError, ValuesError) as e : 
    cleanup_a() 
    cleanup_b() 
    cleanup_c() 
    if type(e) is KeyError: 
     handle_keyerror() 
    else: 
     handle_valueerror() 
+0

多数民众赞成在一个好主意。如果isinstance(e,types.KeyError):'会更好 –

1

如果清除总是可以运行,你可以使用finally子句,它运行的是否引发异常与否:

try: 
    do_something() 
except: 
    handle_exception() 
finally: 
    do_cleanup() 

如果清除应该可以在异常的情况下运行,这样的事情可能工作:

should_cleanup = True 
try: 
    do_something() 
    should_cleanup = False 
except: 
    handle_exception() 
finally: 
    if should_cleanup(): 
    do_cleanup() 
+0

我想过你的第二个选择(用'should_cleanup'标志,它看起来不太可读,长期来看 –

0

如果except块始终是相同的,你可以写:

try: 
    ... 
except (KeyError, ValueError) , e : 
    cleanup_a() 
    cleanup_b() 
    cleanup_c() 
    handle_keyerror() 
+1

不同之处在于handle_keyerror和handle_valueerror,except块不一样 – njzk2