本文主要是介绍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异常处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!