# 示例一: import requests try: # 嘗試進行下面操做,若是能夠執行,就執行下面代碼 ret = requests.get('http://www.google.com') print(ret.text) except Exception as e: # 若是不能夠執行(平時會報錯),這時不會報錯,執行下面代碼 print('請求異常') # 示例二: try: v = [] v[11111] # IndexError類型的異常 except ValueError as e: # ValueError是一個類,繼承Exception,只能捕獲到ValueError類型的異常 pass except IndexError as e: # IndexError是一個類,繼承Exception,只能捕獲到IndexError類型的異常 pass except Exception as e: # Exception是一個類,能夠捕獲到全部異常 print(e) # e是Exception類的對象,存儲了一個錯誤信息
finallypython
try: int('asdf') except Exception as e: print(e) finally: print('最後不管對錯都會執行') # 特殊狀況: def func(): try: int('asdf') except Exception as e: return 123 finally: print('最後') # 不管對錯,函數中遇到return,也會執行,執行完後再return func()
建議:書寫函數或功能時,建議用try包裹一下,避免報錯app
示例函數
# 1. 寫函數,函數接受一個列表,請將列表中的元素每一個都 +100 def func(arg): result = [] for item in arg: if item.isdecimal(): result.append(int(item) + 100) return result # 2. 寫函數去,接受一個列表。列表中都是url,請訪問每一個地址並獲取結果 import requests def func1(url_list): result = [] try: for url in url_list: response = requests.get(url) result.append(response.text) except Exception as e: pass return result def func2(url_list): result = [] for url in url_list: try: response = requests.get(url) result.append(response.text) except Exception as e: pass return result # 這兩個函數執行結果是不同的,是try所處的位置不一樣致使的 func1(['http://www.baidu.com','http://www.google.com','http://www.bing.com']) func2(['http://www.baidu.com','http://www.google.com','http://www.bing.com'])
try: int('123') raise Exception('XXX') # 代碼中主動拋出異常 except Exception as e: print(e) # XXX
示例:google
def func(): result = True try: with open('x.log',mode='r',encoding='utf-8') as f: data = f.read() if 'alex' not in data: raise Exception() except Exception as e: result = False return result
class MyException(Exception): # 自定義異常,繼承Exception pass try: raise MyException('asdf') # 主動觸發自定義異常,只有自定義異常本身和Exception能捕獲到 except MyException as e: print(e)