简体   繁体   English

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

[英]Why is Exception(str()) throwing an exception?

In a CLI application that may or may not be run with a debug parameter, I am catching an exception and selectively rethrowing it: 在可能会或可能不会使用debug参数运行的CLI应用程序中,我正在捕获异常并有选择地将其重新抛出:

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

Interestingly, the raise Exception() code itself is throwing this: 有趣的是, raise Exception()代码本身正在抛出此错误:

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

Would not str(e) return a string? str(e)不会返回字符串吗? I could only imagine that perhaps it is returning None so I tried a general Exception (as seen in the code) hoping that it would never be None. 我只能想象,也许它返回None所以我尝试了一个一般的Exception (如代码所示),希望它永远不会是None。 Why might e not be castable to string ? 为什么会e不被强制转换为string

I think you are misunderstanding the Exception message. 我认为您误解了异常消息。

In your doSomething , an exception raised, the exception is expected string or buffer . doSomething ,引发了一个异常,该异常是expected string or buffer Then you use that string to re-throw an exception. 然后,您使用该字符串重新引发异常。 And you do not catch this exception. 而且您不会捕获此异常。 So, the interpreter stops and print the message. 因此,解释器停止并打印该消息。

>>> 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
>>> 

As a side note, if you want to re-throw an exception, a stand-alone raise statement will do it, which raises the last raised exception. 附带说明一下,如果要重新引发异常,则将执行独立的raise语句,该语句将引发最后引发的异常。 This will give you the actual error as well, rather than just passing the message to Exception . 这也会给您实际的错误,而不仅仅是将消息传递给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

Also, note that everything can be converted to a string (unless you explicitly say it can't ). 另外,请注意,所有内容都可以转换为字符串(除非您明确地说不能 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM