HTTPError是URLError的有一个子类,而URLErro在python3.3后改为OSError的子类。
官方文档提供了两种使用方法(推荐使用第二种):
自己写的测试代码如下:
import urllib.error
import urllib.request
def except_error_1():
try:
urllib.request.urlopen("http://www.imposibale.com")#随意写的url
except urllib.error.HTTPError as e:
print("***Error code: ",e.code)
print("***Reason: ",e.reason)
except urllib.error.URLError as e:
print("***Reason: ",e.reason)
def except_error_2():
try:
urllib.request.urlopen("http://www.imposibale.com")#随意写的url
except urllib.error.URLError as e:
if hasattr(e,"code"):
print("---Error code: ",e.code)
if hasattr(e,"reason"):
print("---Reason: ",e.reason)
except_error_1()
except_error_2()
运行结果:
=============== RESTART: C:\Users\ASUS\Desktop\py\URLError.py ===============
***Reason: [Errno 11001] getaddrinfo failed
---Reason: [Errno 11001] getaddrinfo failed