问题描述
是否可以在Python中捕获任何错误?我不在乎具体的异常是什么,因为所有异常都会有相同的后备.
Is it possible to catch any error in Python? I don't care what the specific exceptions will be, because all of them will have the same fallback.
推荐答案
单独使用except
会捕获除segfault之外的任何异常.
Using except
by itself will catch any exception short of a segfault.
try:
something()
except:
fallback()
您可能需要单独处理KeyboardInterrupt,以防需要使用它退出脚本:
You might want to handle KeyboardInterrupt separately in case you need to use it to exit your script:
try:
something()
except KeyboardInterrupt:
return
except:
fallback()
此处列出了很多不错的基本异常.我也很喜欢 traceback 模块,用于从异常中检索调用堆栈.在异常处理程序中尝试traceback.format_exc()
或traceback.print_exc()
.
There's a nice list of basic exceptions you can catch here. I also quite like the traceback module for retrieving a call stack from the exception. Try traceback.format_exc()
or traceback.print_exc()
in an exception handler.
这篇关于捕获Python中的任何错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!