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