(1)第一種寫法
需要注意的是 在拋出異常的時候,HTTPError必須寫在URLError之前,因為只有這樣前者才能拋出異常,不然的話就會被后者攔截,提前拋出異常。
from urllib.request import Request,urlopen from urllib.error import URLError,HTTPError #請求某一個地址 req = Request(someurl) try: response = urlopen(req) except HTTPError as e: print("The server conldn\'t fulfill the request.") except URLError as e: print('We failed to reach a server.') print('reason:',e.reason) else: #everything is fine
(2)第二種寫法
from urllib.request import Request,urlopen from urllib.error import URLError #請求某一個地址 req = Request("http://xx.baidu.com") try: response = urlopen(req) except URLError as e: if hasattr(e,'reason'): print("We failed to reach a server") elif hasattr(e,'code'): print("The server couldn\'t ful fill the request.") else: print("everything is fine")
hasattr判斷是否擁有這個屬性,如果有的話就打印,如果沒有判斷下一個,建議使用第二個拋異常方法。
