使用Python 3.7.3,仍在弄清楚异常处理的工作原理。
我正在使用slixmpp编写一个xmpp机器人。我正在尝试使其连接到服务器,如果它失去连接,它将尝试重新连接。似乎没有任何方法可以将它内置到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
有人可以告诉我我在做什么错吗?
谢谢!
答案 0 :(得分:1)
我看不到您的导入,但请确保您有from slixmpp.xmlstream.xmlstream import NotConnectedError
,否则在应用程序中没有NotConnectedError
的定义。如果您也不想将其导入,也可以将NotConnectedError
更改为xmpp.xmlstream.xmlstream.NotConnectedError
。