我不太清楚如何在Python中正確使用異常。我想處理我無法完全信任的數據(它們很容易發生變化,如果它們發生變化,腳本可能會中斷)。假設我使用BeautifulSoup處理網頁。如果網站的作者對他的網站進行了一些更改,有些聲明可能會引發異常。讓我們來看看這個代碼示例:現在如何正確處理異常?
data = urllib2.urlopen('http://example.com/somedocument.php').read()
soup = BeautifulSoup(data, convertEntities="html")
name = soup.find('td', text=re.compile(r'^Name$')).parent.nextSibling.string
print name
,如果soup.find()
失敗,因爲該網站的所有者將改變網站的內容,並重新命名細胞Name
到Names
,異常AttributeError: 'NoneType' object has no attribute 'parent'
將得到提升。但我不介意!我預計有些數據將不可用。我只是想繼續和使用哪些變量我有可用的(當然也會有一些數據我所需要的,如果它們是不可用的我就乾脆退出
我想出唯一的辦法就是:
try: name = soup.find('td', text=re.compile(r'^Name$')).parent.nextSibling.string
except AttributeError: name = False
try: email = soup.find('td', text=re.compile(r'^Email$')).parent.nextSibling.string
except AttributeError: email = False
try: phone = soup.find('td', text=re.compile(r'^Phone$')).parent.nextSibling.string
except AttributeError: phone = False
if name: print name
if email: print email
if phone: print phone
有沒有什麼更好的方法,或者我應該繼續作出嘗試,不同的是每類似的聲明它沒有看起來非常漂亮,在所有
編輯:?對我來說最好的解決辦法是這樣的:
try:
print 'do some stuff here that may throw and exception'
print non_existant_variable_that_throws_an_exception_here
print 'and few more things to complete'
except:
pass
這樣會很好,但pass
會跳過try
代碼塊中的任何內容,因此and few more things to complete
將不會被打印。如果出現類似通過的情況,但它會忽略錯誤並繼續執行,那就太好了。
使用'finally'。 http://docs.python.org/tutorial/errors.html#defining-clean-up-actions – sdolan 2011-05-23 23:47:01
「pass會跳過try代碼塊中的任何內容」。正確。爲什麼在'try:'塊中放置這麼多語句? – 2011-05-24 00:40:37