当使用 try
和 except
进行错误处理时,是显式调用 finally
还是直接转到与异常代码分离的新行,这是否重要?例如,有没有什么情况下下面的两个函数会产生不同的结果?
#Function 1 with finally
def final(x):
try:
print(x*x)
except:
print("Error")
finally:
print("End Function")
#Function 2 with new line dedent
def dedent(x):
try:
print(x*x)
except:
print("Error")
print("End Function")
更新:
感谢您对
finally
运行的解释,即使 except
块中有错误。我想指出的另一件事是,即使您在 except 块中返回一个对象, finally
块也会运行。例如,即使在 return
之后,下面的函数 3 也会打印,而函数 4 则不会。#Function 3 with finally
def final(x):
try:
print(x*x)
except:
return 3
finally:
print("End Function 3")
#Function 4 with new line dedent
def dedent(x):
try:
print(x*x)
except:
return 3
print("End Function 4")
test1 = final('test')
test2 = dedent('test')
最佳答案
已经提到的 except
块中存在错误:
def final(x):
try:
print(x*x)
except:
print("Error")
damnit
finally:
print("End Function")
def dedent(x):
try:
print(x*x)
except:
print("Error")
damnit
print("End Function")
try:
final("a")
except Exception as e:
print("There was an error:", e)
#>>> Error
#>>> End Function
#>>> There was an error: global name 'damnit' is not defined
try:
dedent("a")
except Exception as e:
print("There was an error:", e)
#>>> Error
#>>> There was an error: global name 'damnit' is not defined
还有
return
行为:def final(x):
try:
print(x*x)
except:
print("Error")
return "Return inside"
finally:
print("End Function")
return "Return outside"
def dedent(x):
try:
print(x*x)
except:
print("Error")
return "Return inside"
print("End Function")
return "Return outside"
try:
final("a")
except Exception as e:
print("There was an error:", e)
#>>> Error
#>>> End Function
#>>> 'Return outside'
try:
dedent("a")
except Exception as e:
print("There was an error:", e)
#>>> Error
#>>> 'Return inside'
关于Python 错误处理 : finally vs. 新行 dedented,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19038925/