2009-05-05 79 views
6

一些運行時錯誤,我輸入這引起了以下錯誤在一定條件下模塊: RuntimeError:pyparted需要root訪問權限只捕獲在Python

我知道我可以在導入之前檢查的root訪問權限,但我想知道如何通過try/except語句來捕獲這種特殊類型的錯誤以供將來參考。有什麼辦法來區分這個RuntimeError和其他可能會引發的問題嗎?

回答

7

I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised?

如果錯誤是由特定條件造成的,那麼我想捕獲錯誤的最簡單的方法是測試的條件,你可以自己提出一個更具體的錯誤。在拋出錯誤之前存在所有「錯誤」之後,因爲在這種情況下,它存在環境問題。

我同意上面的那些 - 在錯誤上的文本匹配是一種可怕的前景。

4
try: 
    import pyparted 
except RuntimeError: 
    print('RuntimeError is raised') 
    raise 

更多關於exception handling in tutorial

在我看來,這種情況應該會產生ImportError。你可以自己動手:

try: 
    import pyparted 
except RuntimeError as e: 
    raise ImportError(e) 
1

是的。

try: 
     import module 
    except RuntimeError: 
     pass 

導入被解釋爲任何其他語句,它們並不特殊。你可以做一個

if condition: 
    import module 
1
try: 
    import ... 
except RuntimeError: 
    # Do something 
8

您可以檢查異常的屬性,從其他可能RuntimeError異常分化。例如,如果錯誤與預定義的消息文本不匹配,請重新提出錯誤。

try: 
     import pypatred 
    except RuntimeError,e: 
     if e.message == 'RuntimeError: pyparted requires root access': 
      return 'pyparted - no root access' 
     raise 

當然,直接文本比較只是一個例子,您可以搜索包含的子字符串或正則表達式。

值得注意的是,例外的.message屬性爲deprecated starting with Python 2.6。您可以在.args中找到文本,通常爲args[0]

... For 2.6, the message attribute is being deprecated in favor of the args attribute.

+1

並且每次開發人員更改錯誤消息中的字母時,您都需要更改此設置。 – SilentGhost 2009-05-05 17:21:47

0

RuntimeError檢測到錯誤時觸發,不以任何其他類別的下降

def foo(): 
    try: 
     foo() 
    except RuntimeError, e: 
     print e 
     print " Runtime Error occurred due to exceeded maximum recursion depth " 

這就是我們將抓住造成超出遞歸限制的RuntimeError在python

而且如果你想打電話給你的函數在遞歸限制,你可以做以下

import sys 
def foo(): 
    try: 
     foo() 
    except RuntimeError, e: 
     sys.setrecursionlimit(1200) 
     foo() 

但始終這是非常不RECO修改爲改變遞歸限制, 但允許遞歸限制的非常小的變化