finally 语句中的跳转语句 (B012)
源自 flake8-bugbear linter。
作用
检查 finally 代码块中是否有 break、continue 和 return 语句。
为什么这不好?
在 finally 代码块中使用 break、continue 和 return 语句可能会导致异常被静默处理。
无论是否引发异常,finally 代码块都会执行。如果在 finally 代码块中遇到 break、continue 或 return 语句,则在 try 或 except 代码块中引发的任何异常都将被静默处理。
示例
def speed(distance, time):
try:
return distance / time
except ZeroDivisionError:
raise ValueError("Time cannot be zero")
finally:
return 299792458 # `ValueError` is silenced
建议改为
def speed(distance, time):
try:
return distance / time
except ZeroDivisionError:
raise ValueError("Time cannot be zero")