Reputation: 31481
In a CLI application that may or may not be run with a debug
parameter, I am catching an exception and selectively rethrowing it:
try:
doSomething()
except Exception as e:
if debug==True:
raise Exception(str(e))
Interestingly, the raise Exception()
code itself is throwing this:
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? 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. Why might e
not be castable to string
?
Upvotes: 0
Views: 413
Reputation: 32300
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. This will give you the actual error as well, rather than just passing the message to 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).
Upvotes: 2
Reputation: 8610
I think you are misunderstanding the Exception message.
In your doSomething
, an exception raised, the exception is 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
>>>
Upvotes: 4