本套課在線學習視頻(網盤地址,保存到網盤即可免費觀看):
??https://pan.quark.cn/s/ebe046289eb0??
本文詳細介紹了Python編程中try-except-else-finally語句的用法,重點講解了如何通過這些語句對程序中可能出現的異常進行捕獲和處理。特別強調了針對特定類型和未指定類型錯誤的捕獲方法,以及else和finally子句的作用,指出它們在確保代碼穩健性方面的關鍵作用。此外,文章還探討了在爬蟲開發過程中如何利用try-except語句應對請求失敗、服務器響應延遲等異常情況,以提升代碼的穩定性和可靠性。通過實例分析,明確了不論程序是否發生異常,某些代碼片段總是需要被執行的重要性,進而提高了爬蟲的健壯性和效率。
00:00 - 異常捕獲與錯誤處理
異常捕獲的基本用法
程序運行時可能出現各種異常,包括但不限于邏輯錯誤和外部環境導致的問題。異常會導致程序暫停執行并顯示錯誤消息。為了保證程序能夠在遇到異常時繼續運行,可以使用Python中的try-except語句進行異常捕獲。
try:# 可能產生錯誤的代碼result = 10 / 0
except ZeroDivisionError as e:# 捕獲特定類型的錯誤print(f"Error: {e}")
except Exception as e:# 捕獲所有類型的錯誤print(f"An error occurred: {e}")
示例:處理除數為零的錯誤
try:result = 10 / 0
except ZeroDivisionError as e:print(f"Error: {e}")
else:print(f"Result: {result}")
finally:print("Execution completed.")
02:00 - Python異常處理:try except else finally詳解
try-except-else-finally語句
- try: 包含可能產生錯誤的代碼。
- except: 捕獲并處理特定類型的錯誤。
- else: 當try塊中的代碼沒有產生錯誤時執行。
- finally: 無論是否發生錯誤,都會執行。
示例:綜合應用try-except-else-finally
try:result = 10 / 2
except ZeroDivisionError as e:print(f"Error: {e}")
except Exception as e:print(f"An error occurred: {e}")
else:print(f"Result: {result}")
finally:print("Execution completed.")
捕獲所有類型的錯誤
try:result = 10 / 0
except Exception as e:print(f"An error occurred: {e}")
else:print(f"Result: {result}")
finally:print("Execution completed.")
06:30 - 理解并應用異常捕獲機制優化爬蟲
爬蟲中的異常處理
在爬蟲開發過程中,經常會遇到請求失敗或服務器響應延遲等問題,導致程序運行異常。為保證代碼的穩定性和可靠性,引入try-except語句進行異常捕獲至關重要。
示例:爬蟲中的異常處理
import requestsdef fetch_data(url):try:response = requests.get(url, timeout=5)response.raise_for_status() # 檢查響應狀態碼except requests.Timeout as e:print(f"Request timed out: {e}")except requests.RequestException as e:print(f"Request failed: {e}")else:print(f"Response status code: {response.status_code}")return response.textfinally:print("Request completed.")url = "https://example.com"
data = fetch_data(url)
if data:print(data[:100]) # 打印響應內容的前100個字符
重試機制
import requestsdef fetch_data(url, retries=3):for i in range(retries):try:response = requests.get(url, timeout=5)response.raise_for_status()return response.textexcept requests.RequestException as e:print(f"Attempt {i+1} failed: {e}")return Noneurl = "https://example.com"
data = fetch_data(url)
if data:print(data[:100])
else:print("All attempts failed.")
總結
在Python編程中,使用try-except-else-finally語句進行異常捕獲和處理是確保代碼穩健性的關鍵。通過捕獲特定類型和未指定類型的錯誤,并結合else和finally子句,可以有效地處理程序中可能出現的異常情況。在爬蟲開發中,合理應用異常捕獲機制可以顯著提高代碼的穩定性和可靠性,確保在遇到請求失敗、服務器響應延遲等問題時,程序能夠優雅地處理異常并繼續執行。