python - 使用 Errno 在 Python 中打印异常类型

标签 python errno try-except

我目前有格式的代码

try:
    ....
except(HTTPError, URLError, socket.error) as e:
    print "error({0}):{1}".format(e.errno, e.strerror)
continue

但想知道这三个中哪一个触发了异常。有没有办法在 python 中做到这一点?

最佳答案

如果做出不同的 react 对您来说很重要,那么您应该单独捕获它们:

try:
    do_something()
except HTTPError:
    handle_HTTPError()
except URLError:
    handle_URLError()
except socket.error:
    handle socketerror()

但是,如果您只是想显示或记录错误类型及其参数,则应该使用错误的 repr 而不是尝试自己格式化它。例如:

>>> try:
...     raise IOError(911, "Ouch!")
... except IOError as e:
...     print "error({0}):{1}".format(e.errno, e.strerror)
...     print repr(e)
...
error(911):Ouch!
IOError(911, 'Ouch!')

就显示的信息而言,您组合在一起的打印字符串与仅使用 repr 打印的字符串之间几乎没有什么区别。如果您确实想要打印或记录一条“漂亮”的消息,您可以根据自己的喜好操纵字符串,但是 type(e) 不会为您节省任何精力,它不适合显示/日志记录:

>>> type(e)
<type 'exceptions.IOError'>

关于python - 使用 Errno 在 Python 中打印异常类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376853/

相关文章:

python - 使用python写入AWS Lambda中的/tmp目录

delphi - 如何正确编写Try..Finally..Except语句?

python - 如何解决SSL证书错误

python - 排列后如何打印彼此相邻的元组中的值?

Python 桌面应用程序

python - "try"在 "def"之后没有通过

python - 在 python 3 中,使用较短的回溯重新引发错误

python - pytorch 或 Huggingface/transformer 标签代码中的何处将 "renamed"放入标签中?

c - 用于 fgets 失败的最准确的 errno 值是什么?

c - 关于 errno 和 strerror()