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)
posted @ 2022-05-02 16:25  大切切  阅读(21)  评论(0编辑  收藏  举报