如何编写捕获所有异常的 \`try\`/\`except\` 块?

新手上路,请多包涵

我如何编写 try / except 块来捕获所有异常?

原文由 user469652 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 380
2 个回答

你可以,但你可能不应该:

 try:
    do_something()
except:
    print("Caught it!")

然而,这也会捕获像 KeyboardInterrupt 这样的异常,你通常不希望这样,是吗?除非您立即重新引发异常 - 请参阅 文档 中的以下示例:

 try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print("I/O error({0}): {1}".format(errno, strerror))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

原文由 Tim Pietzcker 发布,翻译遵循 CC BY-SA 4.0 许可协议

除了一个裸露的 except: 子句(正如其他人所说你不应该使用的),你可以简单地捕捉 Exception

 import traceback
import logging

try:
    whatever()
except Exception as e:
    logging.error(traceback.format_exc())
    # Logs the error appropriately.

例如,如果您想在终止之前处理任何其他未捕获的异常,您通常只会考虑在代码的最外层执行此操作。

The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit :如果你抓住并吞下了那些东西,那么你可能会让任何人都很难退出你的脚本。

原文由 Duncan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题