python3 异常处理(一)

一、学习链接:

http://docs.python-requests.org/en/master/_modules/requests/exceptions/?highlight=timeout

http://docs.python-requests.org/en/master/api/#requests.Request

http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

https://www.cnblogs.com/zhaof/p/6915127.html

基础类型,常规出现的异常,http://blog.csdn.net/dragonfli_lee/article/details/52350793

知识点补充:

一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组,例如:

except (RuntimeError, TypeError, NameError):
        pass

最后一个except子句可以忽略异常的名称,它将被当作通配符使用。你可以使用这种方法打印一个错误信息,然后再次把异常抛出。





假设,该目录下的文件test.txt不存在



使用 else 子句比把所有的语句都放在 try 子句里面要好,这样可以避免一些意想不到的、而except又没有捕获的异常。

异常处理并不仅仅处理那些直接发生在try子句中的异常,而且还能处理子句中调用的函数(甚至间接调用的函数)里抛出的异常。

该目录下的readme.txt的内容是:





二、BaseException(是一个基类)

理论上来是Exceptioon可以说是python中所有异常的父类,但只是理论,除了Exception派生的异常内置类外还存在按键异常退出,系统异常退出等异常不属于Exception派生的,根据层次结果,可以确认的是,python中所有异常的父类是BaseException(该类是从python2.5新增的),如下给出内置异常处理类的基本层次结构。

在Python中,各种异常错误都是类,所有的错误类型都继承于BaseException。

try:
    dictmsg={}    
    ......
except BaseException:
    dictmsg["result"]="fail";
    dictmsg["response"]={"failreason":"BaseException"};
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
      |    +-- ImportError
      |    +-- LookupError
      |    |    +-- IndexError
      |    |    +-- KeyError
      |    +-- MemoryError
      |    +-- NameError
      |    |    +-- UnboundLocalError
      |    +-- ReferenceError
      |    +-- RuntimeError
      |    |    +-- NotImplementedError
      |    +-- SyntaxError
      |    |    +-- IndentationError
      |    |         +-- TabError
      |    +-- SystemError
      |    +-- TypeError
      |    +-- ValueError
      |         +-- UnicodeError
      |              +-- UnicodeDecodeError
      |              +-- UnicodeEncodeError
      |              +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
	   +-- ImportWarning
	   +-- UnicodeWarning
	   +-- BytesWarning

三、requests发生的异常:

Timeout是即捕获ConnectTimeout连接超时又捕获ReadTimeout连接后等不到返回内容的超时

try:
  requests.post(url, headers, timeout=10)
except requests.exceptions.Timeout:
  print "Timeout occurred"
四、
from requests.exceptions import *
import requests
                                        try:
						ret=requests.post(posturl.handlerurl[0], data=datadict,timeout=(5,5))#返回<Response [200]>,ret.content类型是bytes(加密的数据类型)
						print (ret.content)
						paramt=str(ret.content,'UTF-8').replace('\r\n','')
						#paramt=paramt.encode('UTF-8')
						responsedt=obj.descypt(paramt)
						if responsedt==None:#贝哥返回加密串问题
							resultstr="UnicodeEncodeError: 'ascii' codec can't encode characters"
							dict["result"]="fail";
							dict["response"]={"failreason":resultstr};
						else:
							responsedt=eval(responsedt)
							if responsedt["WxChatURL"]=='' or responsedt["AliPayURL"]=='':
								dict["result"]="fail";
								dict["response"]={"failreason":"The QR code is empty"};
								dict =json.dumps(dict);
								return HttpResponse(dict)
							print(responsedt)
							responsedt["BillId"]=BillId
							dict["result"]="success";
							dict["response"]=responsedt
					except ReadTimeout:#服务器没有在指定的时间内发送任何数据。
						resultstr="The next server did not send any data within the specified time"
						dict["result"]="fail";
						dict["response"]={"failreason":resultstr};
					except Timeout:#请求超时。捕获此错误将同时捕获ConnectTimeout和ReadTimeout错误。
						resultstr="Connect and Read Timeout!"
						dict["result"]="fail";
						dict["response"]={"failreason":resultstr};
					except ConnectionError:#当出现了网络问题,比如 dns错误 拒绝访问等
						resultstr="The front server can not connect to the next server"
						dict["result"]="fail";
						dict["response"]={"failreason":resultstr};
					except HTTPError:#HTTP返回不成功的状态,
						resultstr="HTTP status of the next server is error"
						dict["result"]="fail";
						dict["response"]={"failreason":resultstr};
					except URLRequired:#发出请求需要有效的URL
						resultstr="A valid URL is required to make a request"
						dict["result"]="fail";
						dict["response"]={"failreason":resultstr};
					except ConnectTimeout:#尝试连接到远程服务器时,请求超时。
						resultstr="Request timed out while connecting to a remote server"
						dict["result"]="fail";
						dict["response"]={"failreason":resultstr};
					# except requests.UnicodeEncodeError:
						# resultstr="UnicodeEncodeError!"
						# dict["result"]="fail";
						# dict["response"]={"failreason":resultstr};
					except RequestException:#exceptions.
						resultstr="Other exceptions occurred"
						dict["result"]="fail";
						dict["response"]={"failreason":resultstr};
					# if ret.status_code!=200:
						# resultstr="The front server can not connect to the next server"
						# dict["result"]="fail";
						# dict["response"]=resultstr
						# dict =json.dumps(dict);
						# return HttpResponse(dict)
					dict =json.dumps(dict);
					return HttpResponse(dict)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值