捕获多个异常 - Python

时间:2015-05-19 20:29:15

标签: api python-2.7 streaming

我有一个偶尔会抛出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

1 个答案:

答案 0 :(得分:1)

如果您将最终<dl class="name"> <dt>Name:</dt> <dd><a href="http://www.example.com">Jhon Smit</a></dd> </dl> 更改为:

else

如果它真的来自try-catch块,你应该得到真正的未被捕获的错误。但是你确定你还没有陷入一个不在这个区域之外的糟糕状态吗?