处理异常
1. URLError
URLEroor
来自urllib
库的error
模块,它继承自OSError
类,是error
异常模块的基类,由request
模块生成的异常可以通过捕获这个类来处理。
他的属性reason
,可以返回错误的原因。
下面展示一个例子:
from urllib import request,error
try :
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
print(e.reason)
我们打开一个不存在的页面,照理来说应该报错,但是我们捕获了URLError
这个异常,云个性结果如下:
Not Found
程序没有直接报错,而是输出了如上内容,我们就可以避免程序异常终止,同时异常得到了有效处理。
2. HTTPError
它是URLError
的子类,专门用来处理HTTP
请求错误,比如请求认证失败。他有如下3个属性
code
: 返回HTTP
状态码。比如404表示网页不存在,500表示服务器内部错误等。reason
: 同父类一样,用于返回错误的原因。headers
: 返回请求头
下面看一个例子:
from urllib import request,error
try :
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
print(e.reason,e.code,e.headers,sep= '\n')
运行结果如下:
Not Found
404
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 03 Aug 2016 08:54:22 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
X-Powered-By: PHP/5.5.9-1ubuntu4.14
Vary: Cookie
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Pragma: no-cache
Link: <http://cuiqingcai.com/wp-json/>; rel="https://api.w.org/"
依然是同样的网址,这里捕获了HTTPError
异常,输出了reason
, code
, headers
属性。因为URLError
是HTTPError
的父类,所以可以选择捕获子类的错误,再去捕获父类错误,再去捕获父类的错误,所以上述代码最好的写法如下:
from urllib import request,error
try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
else :
print('Request successfully!')
这样就可以先捕获HTTPError
,获取它的错误状态码、原因、headers
等信息。入股哦不是HTTPError
异常,就会捕获URLError
异常,输出错误原因。最后用else来
处理正常的逻辑。这是一个较好的异常处理写法。
有时候reason属性返回的不一定是字符串,也可能是一个对象。再看看下面的示例:
import socket
import urllib.error
import urllib.request
try :
response = urllib.request.urlopen('http://www.baidu.com',timeout= 0.01)
except urllib.error.URLError as e:
print(type(e.reason))
if isinstance(e.reason,socket.timeout):
print('Time out')
在这个例子里,我们设置超出时间来强制抛出timeout
异常。
运行结果如下
<class 'socket.timeout'>
Time out
可以发现,reason
属性的直接结果是socket.timeout
类。所以,这里我们可以用isinstance()
方法来判断它的类型,做出更详细的异常判断.
参考崔庆才个人博客