如何根据 Python 3 中的字符串参数捕获一般异常?

How to catch a general Exception based on its string argument in Python 3?

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

如何仅在字符串参数为 "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

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

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

嗯,理想情况应该是引发自定义异常。由于情况并非如此,解决方法可以是检查异常消息。

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