捕获多个异常 - Python

Catching multiple exceptions - Python

我有一个程序偶尔会抛出 badStatusLine 异常,在捕获它之后我们现在又遇到了另一个错误,我似乎无法捕获它所以程序不会停止。这是我的资料,如有任何帮助,我们将不胜感激。

错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/Users/mattduhon/trading4.py", line 30, in trade
    execution.execute_order(event)
  File "/Users/mattduhon/execution.py", line 33, in execute_order
    params, headers
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1001, in request
    self._send_request(method, url, body, headers)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1029, in _send_request
    self.putrequest(method, url, **skips)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 892, in putrequest
    raise CannotSendRequest()
CannotSendRequest

负责捕获错误的文件:

import httplib
import urllib
from httplib import BadStatusLine
from httplib import CannotSendRequest

class Execution(object):
    def __init__(self, domain, access_token, account_id):
        self.domain = domain
        self.access_token = access_token
        self.account_id = account_id
        self.conn = self.obtain_connection()

    def obtain_connection(self):
        return httplib.HTTPSConnection(self.domain)

    def execute_order(self, event):
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Bearer " + self.access_token}
        params = urllib.urlencode({
            "instrument" : event.instrument,
            "units" : event.units,
            "type" : event.order_type,
            "side" : event.side,
            "stopLoss" : event.stopLoss,
            "takeProfit" : event.takeProfit
        })
        self.conn.request(
            "POST",
            "/v1/accounts/%s/orders" % str(self.account_id),
            params, headers)
        try:
            response = self.conn.getresponse().read()  
        except BadStatusLine as e:
            print(e)
        except CannotSendRequest as a:  ######my attempt at catching the error
            print(a)
        else:          
            print response

如果将最后的else改为:

except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

如果它真的来自 try-catch 块,您应该得到真正的未捕获错误。但是你确定你没有进入那个街区之外的糟糕状态吗?