在python 3中捕获异常时遇到问题

问题描述 投票:0回答:1

使用Python 3.7.3,仍然可以找出异常处理的工作原理。

我正在使用slixmpp编写一个xmpp bot。我试图这样做,如果它失去与服务器的连接,它将尝试重新连接。似乎没有任何方法可以在slixmpp中内置这个,所以我在自己的代码中写了一些东西来做。

我已经将slixmpp导入为xmpp,并使用它的send_raw()方法来测试我们是否仍然连接到服务器。

    while True:
        time.sleep(5)  # Send every 5 seconds just for testing purposes
        xmpp.send_raw('aroo?')

当我切断与服务器的连接时,这是它吐出的内容:

    Traceback (most recent call last):
      File "C:\Program Files\Python37\lib\threading.py", line 917, in _bootstrap_inner
        self.run()
      File "testcom.py", line 19, in run
        eval(self.thing)()
      File "testcom.py", line 28, in check_conn
        xmpp.send_raw('aroo?')
      File "C:\Program Files\Python37\lib\site-packages\slixmpp\xmlstream\xmlstream.py", line 926, in send_raw
        raise NotConnectedError
    slixmpp.xmlstream.xmlstream.NotConnectedError   

我假设“NotConnectedError”是我需要捕获的异常,所以我将代码放在try块中,如下所示:

    try:
        while True:
            time.sleep(5)  # Send every 5 seconds just for testing purposes
            xmpp.send_raw('aroo?')
    except NotConnectedError:
        # Do a thing
        pass

这就是我得到的:

    Traceback (most recent call last):
      File   "testcom.py", line 28, in check_conn
        xmpp.send_raw('aroo?')
      File "C:\Program Files\Python37\lib\site-packages\slixmpp\xmlstream\xmlstream.py", line 926, in send_raw
        raise NotConnectedError()
    slixmpp.xmlstream.xmlstream.NotConnectedError                                                                                             

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\Program Files\Python37\lib\threading.py", line 917, in _bootstrap_inner
        self.run()
      "testcom.py", line 19, in run
        eval(self.thing)()
      File "testcom.py", line 29, in check_conn
        except NotConnectedError:
    NameError: name 'NotConnectedError' is not defined

谁能告诉我这里我做错了什么?

谢谢!

python-3.x exception
1个回答
1
投票

我看不到你的进口,但确保你有from slixmpp.xmlstream.xmlstream import NotConnectedError,否则它在应用程序中没有NotConnectedError的定义。如果您不想将NotConnectedError导入xmpp.xmlstream.xmlstream.NotConnectedError,也可以将其更改为qazxswpoi。

© www.soinside.com 2019 - 2024. All rights reserved.