python使用try except捕捉错误,当发现错误时无需从底层向上依次返回错误代码,而是直接抛出异常。
通常使用方法;
try:执行语句,发生错误时后续语句不在执行,转至except
except : 处理该类型的错误
except :
else: 无错误发生时执行此处
finally: 不管有无错误都会执行
错误类型见:https://docs.python.org/3/library/exceptions.html#exception-hierarchy
2.采用断言assert
assert 表达式,‘出错提示语句’
def f(x): assert x != 0, 'x is zero' f(0)
AssertionError: x is zero
3.logging