python異常處理的兩種寫法


(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判斷是否擁有這個屬性,如果有的話就打印,如果沒有判斷下一個,建議使用第二個拋異常方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM