2013-07-21 146 views
0

在可以或可以不與一個debug參數運行CLI應用,我捕獲異常並選擇性地重新拋出它:爲什麼Exception(str())拋出異常?

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(如代碼所示),希望它永遠不會成爲無。爲什麼e不能澆注到string

+4

'str(e)=='預期的字符串或緩衝區'。你的代碼工作正常。 – Volatility

回答

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

+0

謝謝!我選擇這個作爲答案,因爲你確實提出了改進代碼的方法。 – dotancohen

+0

持續引發的異常不是特定的。一個獨立的提高將重新提出目前正在處理的例外情況。如果超出,則會出現錯誤。 – zhangyangyu

+0

@張揚餘,但即使異常被提出,然後處理之前,它被重新加註。舉例來說[這個ideone](http://ideone.com/M0cFF2) – Volatility

4

我認爲你誤解了Exception消息。

在您的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 
>>> 
+0

謝謝zhangyangyu。現在我明白了這是怎麼回事,這幾乎是有趣的! – dotancohen

相關問題