为什么Exception(str())抛出异常?

时间:2013-07-21 13:18:31

标签: python exception

在可能使用debug参数运行或不运行的CLI应用程序中,我捕获异常并有选择地重新抛出它:

try:
    doSomething()
except Exception as e:
    if debug==True:
        raise Exception(str(e))

有趣的是,raise Exception()代码本身就是这样:

Traceback (most recent call last):
  File "./app.py", line 570, in getSomething
    raise Exception(str(e))
Exception: expected string or buffer

str(e)不会返回字符串吗?我只能想象它可能正在返回None所以我尝试了一般Exception(如代码所示),希望它永远不会是None。为什么e无法转换为string

2 个答案:

答案 0 :(得分:4)

我认为你误解了异常消息。

在您的doSomething中,引发了异常,例外是expected string or buffer。然后使用该字符串重新抛出异常。你没有抓住这个例外。因此,解释器停止并打印消息。

>>> try:
...     raise Exception('expected string or buffer')
... except Exception as e:
...     raise Exception(str(e))
... 
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
Exception: expected string or buffer
>>> 

答案 1 :(得分:2)

作为旁注,如果你想重新抛出一个异常,那么一个独立的raise语句会执行它,这会引发最后一次引发的异常。这也将为您提供实际错误,而不仅仅是将消息传递给Exception

try:
    doSomething()
except:  # except by itself catches any exception
         # better to except a specific error though
    if debug:  # use implicit truth check of `if`
        raise  # re-raise the caught exception

另请注意,所有内容都可以转换为字符串(除非explicitly say it can't)。