python - 捕获 Python 中的任何错误

标签 python exception exception-handling try-catch fallback

是否可以在 Python 中捕获 any 错误?我不在乎具体的异常(exception)是什么,因为它们都有相同的回退。

最佳答案

单独使用 except 将捕获任何没有段错误的异常。

try:
    something()
except:
    fallback()

您可能需要单独处理 KeyboardInterrupt 以防您需要使用它来退出脚本:

try:
    something()
except KeyboardInterrupt:
    return
except:
    fallback()

有一个很好的基本异常列表,您可以捕获 here .我也很喜欢traceback用于从异常中检索调用堆栈的模块。在异常处理程序中尝试 traceback.format_exc()traceback.print_exc()

关于python - 捕获 Python 中的任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6817640/

相关文章:

php - 将 PHP 7 错误对象转换为异常?

java - Spring/JPA/JSF 的异常处理策略

python - 在pygame中移动角色而不重复复制图像

python - 无法让 nginx 缓存 uwsgi 结果

c# - Windows Phone 7 应用程序崩溃但在调试时没有

c# - Response.Redirect 结果在 "Object moved to here"

java - 嵌套的 try 异常是否会被外部 catch block 捕获

java - Spring MVC 中的嵌套异常处理

python - 如何将统计输出转换为 unix 权限字符串

python - tf.constant 与 tf.placeholder