python 3異常処理(一)

8615 ワード

一、学習リンク:
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.
https://www.cnblogs.com/zhaof/p/6915127.html
基本タイプ、常規に発生する異常、http://blog.csdn.net/dragonfli_lee/articale/detail/52350739
知識ポイント追加:
一つのexcept子文は同時に複数の異常を処理できます.これらの異常は括弧の中に入れて一つの元のグループになります.例えば、
except (RuntimeError, TypeError, NameError):
        pass
最後のexcept子文は異常な名前を無視できます.ワイルドカードとして使用されます.この方法でエラーメッセージを印刷して、再度異常を投げ出してもいいです.
python3 异常处理(一)_第1张图片
python3 异常处理(一)_第2张图片
python3 异常处理(一)_第3张图片
このディレクトリの下のファイルtest.txtが存在しないと仮定します.
python3 异常处理(一)_第4张图片
else子文を使うと、すべての語句をtry子文に入れるよりもいいです.これは思いがけないことで、exceptに捕獲されていない異常を避けることができます.
異常処理は、try子文に直接発生する異常だけでなく、サブカルで呼び出された関数(または間接的に呼び出された関数)に投げかける異常を扱うことができます.
このディレクトリの下のreadme.txtの内容は以下の通りです.
python3 异常处理(一)_第5张图片
python3 异常处理(一)_第6张图片
二、BaseException(ベースクラスです)
理論的にはExceptionはpythonの中の異常なすべての親類といえるが、理論だけでは、Exceptionから派生した異常な内蔵類のほかにボタン異常終了、システム異常終了などの異常はExceptionの派生ではなく、レベルの結果から、pythonの中の異常なすべての父親類はBaseExceptionであることが確認されている.異常処理クラスを内蔵する基本的な階層構造を以下に示します.
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
python3 异常处理(一)_第7张图片
三、requestsに発生する異常:
Timeoutは、Connect Timeoutを捕獲して接続がタイムアウトし、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))#  ,ret.content   bytes(       )
						print (ret.content)
						paramt=str(ret.content,'UTF-8').replace('\r
','') #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)