目前,我有一些类似的代码
try:
somecode
except Exception as Error:
fallbackcode
现在,我想向后备代码添加另一个后备代码 在python中进行嵌套try / catch的最佳实践是什么?
try:
somecode
except Exception as Error:
try:
fallbackcode
except Exception as Error:
nextfallbackcode
产生意图错误
答案 0 :(得分:1)
您应该能够完全按照问题的实现方式来进行嵌套的try / except块。
这是另一个例子:
import os
def touch_file(file_to_touch):
"""
This method accepts a file path as a parameter and
returns true/false if it successfully 'touched' the file
:param '/path/to/file/'
:return: True/False
"""
file_touched = True
try:
os.utime(file_to_touch, None)
except EnvironmentError:
try:
open(file_to_touch, 'a').close()
except EnvironmentError:
file_touched = False
return file_touched
答案 1 :(得分:0)
如果所有回调和后备具有相同的API接口,则可以使用循环来重写逻辑
for code in [somecode, fallbackcode, nextfallbackcode]:
try:
code(*args, **kwargs)
break
except Exception as Error:
continue
else:
raise HardException
这是首选方法,而不是多层嵌套异常块。
答案 2 :(得分:0)
您可以这样更改它:
try:
try:
somecode
except Exception as Error:
fallbackcode
except Exception as Error:
nextfallbackcode
答案 3 :(得分:0)
您可以使用函数来处理错误:
def func0():
try:
somecode
except:
other_func()
def func1():
try:
somecode
except:
func0()