2014-04-18 53 views
1

有沒有一種方法可以在向鏈傳遞內部異常時提供有關內部異常的原因的信息(例如,可能在具有Exception類cause屬性的java中)。Python中嵌套異常的嵌套原因

請考慮下面的「蟒蛇僞代碼」(沒有100%的正確,併發明瞭函數和類名)

try: 
    clientlib.receive_data_chunk() 
except ClientException as clientException: 
    raise RuntimeError("reading from client failed" 
     + " (see nested exceptions for details)", cause=clientException) 

和clientlib.py

def receive_data_chunk(): 
    try: 
    chunk = socket.read(20) 
    return chunk 
    except IOException as iOException: 
    raise ClientException("couldn't read from client", cause = iOException) 

如果沒有在本地蟒蛇什麼將是實現我想要做的最佳實踐?

請注意,我想保存內部和外部異常兩個蹤跡,即下面的解決方案是不令人滿意的:

import sys 

def function(): 
    try: 
     raise ValueError("inner cause") 
    except Exception: 
     _, ex, traceback = sys.exc_info() 
     message = "outer explanation (see nested exception for details)" 
     raise RuntimeError, message, traceback 

if __name__ == "__main__": 
    function() 

只產生以下的輸出:

Traceback (most recent call last): 
    File "a.py", line 13, in <module> 
    function() 
    File "a.py", line 6, in function 
    raise ValueError("inner cause") 
RuntimeError: outer explanation (see nested exception for details) 

我無法看到RuntimeError發生在哪裏,所以在我的理解中,外部堆棧跟蹤丟失。

+0

看到這個(HTTP://計算器.com/questions/1350671 /內部異常與追溯在蟒蛇)問題,詢問並回答你想知道的(只是用不同的術語)。 – wheaties

+0

我同意。我想這是有道理的編輯引用的問題的標題,以包括術語'原因',以改善搜索,因爲它是安靜廣泛用於Java相關的問題。 –

回答

4

在Python 3,你可以使用from關鍵字來指定一個內部異常:

raise ClientException(...) from ioException 

你得到一個回溯,看起來像這樣:

Traceback (most recent call last): 
    ... 
IOException: timeout 

The above exception was the direct cause of the following exception: 

Traceback (most recent call last): 
    ... 
ClientException: couldn't read from client 
+0

太好了,那正是我要找的! –