python异常处理
作者:互联网
异常处理
异常处理格式一(最常用)
try:
idc = IDC.objects.get(pk=pk)
except Exception as e:
return APIResponse(code=-1, message=f"pk Error({e})")
异常处理格式二
try:
<代码块(被检测的代码块)>
except 异常类型:
<代码块>
finally:
<代码块>
异常处理格式三(多分支)
try:
<代码块(被检测的代码块)>
except IndexError as e:
<代码块>
except KeyError as e:
<代码块>
except ValueError as e:
<代码块>
抛出异常(assert)
>>> a=0
>>> assert a > 0,"a小于0"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: a小于0
抛出异常(raise)
try:
raise TypeError('抛出异常,类型错误')
except Exception as e:
print(e)
标签:python,抛出,except,try,处理,pk,异常 来源: https://www.cnblogs.com/bigcarcar/p/16216077.html