2014-07-02 75 views
0

我有一個例外,我試圖得到參數,但如果失敗。如何檢查元組是否具有元素?

print hasattr(e, 'args') 
print type(e.args) 
print hasattr(e.args, '1') 
print hasattr(e.args, '0') 
print '1' in e.args 
print '0' in e.args 
print 1 in e.args 
print 0 in e.args 
print e.args[0] 
print e.args[1] 

此打印:

True 
<type 'tuple'> 
False 
False 
False 
False 
False 
False 
Devices not found 
4 
+0

可能的重複[要檢查列表的索引是否存在](http://stackoverflow.com/questions/19565745/to-check-whether-index-of-list-exists) – vaultah

+0

我不確定你想。你想檢查'e.args [N]'是否存在,或者你想檢查一個特定的值是否是'e.args'的一部分? – netcoder

+0

@netcoder拳頭,如果'e.args [0]'存在 – Kin

回答

1

您只需使用in操作:

>>> try: 
... raise Exception('spam', 'eggs') 
... except Exception as inst: 
... print inst.args 
... print 'spam' in inst.args 
... 
('spam', 'eggs') 
True 

如果您的代碼返回False那麼最有可能1不是一個參數例外。也許在發生異常的地方發佈代碼。

您可以通過執行len來檢查元組是否具有位置0N

+0

你可以看到'print e.args [0]'打印結果,所以我需要檢查是否存在[0] – Kin

+0

爲什麼不檢查元組的'len'。然後你知道哪些索引存在(最多len-1) –

0

您可以檢查您的元組的長度:

t = 1, 2, 3, 
if len(t) >= 1: 
    value = t[0] # no error there 

...或者你可以只檢查一個IndexError,我會說是更Python:

t = 1, 2, 3, 
try: 
    value = t[4] 
except IndexError: 
    # handle error case 
    pass 

後者是一個名爲EAFP: Easier to ask for forgiveness than permission的概念,這是一種衆所周知的通用Python編碼風格。