基本异常处理语句
python
的基本异常处理语句为:
import traceback
from random import randint
try:
if randint(0,1):
raise ZeroDivisionError("test")
except Exception as e:
# 捕获异常
print("\n========error_info========")
print("{}:{}".format("e_str",str(e)))
print("{}:{}".format("e_repr",repr(e)))
print("{}:{}".format("e_traceback",traceback.format_exc()))
print("========error_info========\n")
else:
# 如果代码没有异常执行这部分
print("exec if no Exception")
finally:
# 这部分不论如何都会被执行
print("exec this field anyway")
存在异常时输出:
(base) ~/.../manjaro_workspace/py100 >>> python test12.py
========error_info========
e_str:test
e_repr:ZeroDivisionError('test')
e_traceback:Traceback (most recent call last):
File "test12.py", line 4, in <module>
raise ZeroDivisionError("test")
ZeroDivisionError: test
========error_info========
exec this field anyway
重新捕获在异常处理时抛出的异常
每个异常处理域只能处理一个异常,即使这个异常是在我们进行异常处理时抛出的,因为Python
的异常处理在经过一个Exception
域之后就会跳过此异常处理域中剩下的Exception
域,要处理多个异常,需要进行异常处理的嵌套
try:
try:
raise ZeroDivisionError("test ZeroDivisionError")
except ZeroDivisionError as e:
# 内部域捕获异常
print("catch Exception {}".format(e))
raise ValueError("test ValueError")
except ValueError as e:
# 内部域无法捕获在其所在的异常处理域内触发的异常
print("recatch Exception @inner_field")
except ValueError as e:
# 外部域
print("catch Exception {}@outter_field".format(e))
输出:
(base) ~/.../manjaro_workspace/py100 >>> python test12.py
catch Exception test ZeroDivisionError
catch Exception test ValueError@outter_field
如何捕获系统级别的异常
一般进行异常处理时使用我们确定可能会触发的异常就可,捕获全部的基本异常使用Exception
,如果想捕获系统级别的异常,需要使用BaseException
,如具体关系如下图
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- ValueError
+-- ...
异常处理的一般规范
- 能不使用异常就不使用异常
- 抛出异常时要明确异常类型和内容