2011-10-07 22 views
3

如果不是所有必須對其執行的操作都成功(即引發異常),我需要刪除文件。這可能與使用一樣簡單,除了:,刪除文件然後重新引發異常,但在這種情況下,如果文件不能在中被刪除,除了子句,無論出於任何神祕原因。僅在引發異常時清除對象

,我已經能夠拿出最好的是這樣的:

try: 
    file_path = "whatever.jpg" 
    # do stuff with file 
except: 
    exception_raised = True 
    raise 
finally: 
    try: 
     if exception_raised: 
      os.unlink(file_path) 
    except: 
     pass 

return file_path # everything OK 

是否有人知道一個更好的,更Python的方法呢?

回答

5

另一種選擇是簡單地存儲異常,如果你不想失去它:

的Python 3.x版:

try: 
    file_path = "whatever.jpg" 
    # do stuff with file 
except BaseException as e: 
    try: 
     os.unlink(file_path) 
    except Exception: 
     traceback.print_exc() 
    raise e 

Python的2.x版稍微因爲更復雜你需要手動存儲完整的異常信息(否則你會失去回溯):

try: 
    file_path = "whatever.jpg" 
    # do stuff with file 
except: 
    e = sys.exc_info() 
    try: 
     os.unlink(file_path) 
    except Exception: 
     traceback.print_exc() 
    raise e[0], e[1], e[2] 

編輯:僅捕獲因爲你不想在這裏捕獲SystemExitKeyboardInterrupt,所以在try區塊內的Exception的子類。還要報告在取消鏈接期間發生的任何改變,而不是放棄它。

+0

當然,這不適用於不是從'BaseException'派生的異常。 – Mankarse

+0

@Mankarse:在Python 3中,所有異常都必須從BaseException派生。在Python 2中,異常類必須從'BaseExcpetion'派生或者是舊式類。舊樣式類現在已經停用了十年,所以如果您不使用使用奇怪異常類的舊*庫,上述代碼應該相當安全。 –

+0

@Mankarse:Python 2.x的代碼有一個不同的問題 - 異常的追蹤丟失了。修復這個問題也會將(次要)限制移除到'BaseException'。 –

相關問題