我在pydoc中查找了sys,因为我正在阅读的一本书推荐给我,我遇到了last_type这是最后一个未捕获异常的类型,我的问题是pydoc / python中什么是未捕获的异常以及它用于什么?
未捕获的异常只是try-except语句中的except-handler未处理的每个异常,因此会导致脚本停止。
如果发生这种情况,默认情况下解释器会输出异常类型,错误消息和回溯。
因此,如果您尝试使用print(1/0)
,您将获得类型为ZeroDivisionError
的异常,错误消息“除以零”以及导致异常(追溯)的代码的最后一步。
print(1/0)
Traceback (most recent call last):
File "E:\Programme\Anaconda3\envs\py36\lib\site-
packages\IPython\core\interactiveshell.py", line 2910, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-12-2fc232d1511a>", line 1, in <module>
print(1/0)
ZeroDivisionError: division by zero
未捕获的异常会让您知道出现了问题。然后,您必须删除错误源(可能您实际上想要编写print(1/10)
,或者您必须捕获并处理异常,允许您的程序继续执行错误源下的代码。
try:
1/0
except ZeroDivisionError as err: # error is caught here
pass # e.g just do nothing
# print(type(err).__name__, flush=True) # or do something, like print
# error type
print("will be printed because exception before was caught")