【问题标题】:Exception not intercepted by try: except:try: 未拦截的异常:
【发布时间】:2021-05-22 23:06:48
【问题描述】:

我创建了一个严重依赖 asyncio 的应用,它使用了额外的第三方库,该库也依赖于 asyncio(处理 websocket)。

打开几个 websocket,我的代码运行良好。当我增加 websocket 的数量时,我开始遇到一些异常。为了调试异常,我尝试用try:except ValueError: 包围我的代码中生成异常的行,并在异常部分放置断点。

例如,这里引发了异常

Exception in callback AsyncIOEventEmitter._emit_run.<locals>._callback(<Task finishe...id indices',)>) at [XXX]\Python36\lib\site-packages\pyee-8.1.0-py3.6.egg\pyee\_asyncio.py:55
handle: <Handle AsyncIOEventEmitter._emit_run.<locals>._callback(<Task finishe...id indices',)>) at [XXX]\Python36\lib\site-packages\pyee-8.1.0-py3.6.egg\pyee\_asyncio.py:55>
Traceback (most recent call last):
  File "[XXX]\Python36\lib\asyncio\events.py", line 145, in _run
    self._callback(*self._args)
  File "[XXX]\Python36\lib\site-packages\pyee-8.1.0-py3.6.egg\pyee\_asyncio.py", line 62, in _callback
    self.emit('error', exc)
  File "[XXX]\Python36\lib\site-packages\pyee-8.1.0-py3.6.egg\pyee\_base.py", line 116, in emit
    self._emit_handle_potential_error(event, args[0] if args else None)
  File "[XXX]\Python36\lib\site-packages\pyee-8.1.0-py3.6.egg\pyee\_base.py", line 86, in _emit_handle_potential_error
    raise error
  File "[XXX]\arbitrager.py", line 48, in order_book_update
    opportunity_update(data, False)
  File "[XXX]\arbitrager.py", line 62, in opportunity_update
    np.where(symbols.paths['symbol4'] == data['symbol'])[0],
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

所以我更新了我的代码,结果如下:

try:
    index = np.unique(np.concatenate([
        index,
        np.where(symbols.paths['symbol1'] == data['symbol'])[0],
        np.where(symbols.paths['symbol2'] == data['symbol'])[0],
        np.where(symbols.paths['symbol3'] == data['symbol'])[0],
        np.where(symbols.paths['symbol4'] == data['symbol'])[0],
        np.where(symbols.paths['symbol5'] == data['symbol'])[0]
    ]))
except ValueError:
    print("oups") #put a breakpoint here

当我再次运行我的代码时,我仍然会同时引发异常,而不会触发断点

知道为什么try: except: 没有捕获到异常吗? 请注意,我并不是在寻求有关异常含义的帮助,我只是想访问断点以便调试值。

【问题讨论】:

  • 您的except 捕获ValueError,但try 下的代码引发IndexError

标签: python exception


【解决方案1】:

嗯,好像你排除了ValueError

except ValueError:
    print("oups")

但你的错误是IndexError。所以明显的改变是纠正你的例外。

except IndexError:
    print("oups")

此外,如果您想知道发生了什么错误,可以使用如下所示的内容。

except Exception as e:
    print(type(e).__name__)

根据输出,您可以更改要接受的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2019-04-11
    • 1970-01-01
    • 2010-09-18
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多