【问题标题】:How to catch a general Exception based on its string argument in Python 3? [duplicate]如何根据 Python 3 中的字符串参数捕获一般异常? [复制]
【发布时间】:2017-10-04 13:04:25
【问题描述】:

我正在与引发如下异常的 API 通信:raise Exception("end of time")

仅当字符串参数为“时间结束”时,我如何捕获Exception

我不想做:

except Exception:
    pass

我想做这样的事情:

except Exception("end of time"):
    pass

但是,这并没有捕捉到异常。

示例回溯:

File "test.py", line 250, in timeout_handler
    raise Exception("end of time")
Exception: end of time

【问题讨论】:

  • @vaultah 指向重复问题的链接不合适,因为答案不适用于 Python 3。
  • 添加了另一个。希望 mgilson 能更新他的答案。

标签: python python-3.x exception exception-handling


【解决方案1】:

如果需要,请使用 Exception .args 过滤内容:

try:
    raise Exception("end of time")
except Exception as e:
    if e.args[0] == 'end of time':
        pass # handle
    else:
        raise

【讨论】:

  • str(e) 也很好用。
  • @Jean-François Fabre 如果len(e.args) > 1 怎么办?
【解决方案2】:

好吧,理想的情况应该是引发自定义异常。由于情况并非如此,因此可以检查异常消息。

except Exception as exp:
    if str(exp) == 'end of time':
        # do something
    else:
        # pass or do something else

【讨论】:

  • message 属性仅在 Python 2 中可用。
  • @MosesKoledoye 不知道。更新了我的答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 2021-02-12
  • 2010-11-01
  • 1970-01-01
  • 2011-01-03
相关资源
最近更新 更多