0
我是Python開發新手,並試圖找出如何捕獲線程內的ConnectionError,然後退出。目前我擁有它,因此它可以捕獲一般異常,但我想爲不同的異常指定不同的異常處理,並且還會停止某些類型的異常的應用程序。Python線程捕捉異常並退出
我目前正在使用線程,但我開始懷疑我是否應該使用多線程呢?
下面是代碼的副本:
import threading
import sys
from integration import rabbitMq
from integration import bigchain
def do_something_with_exception():
exc_type, exc_value = sys.exc_info()[:2]
print('Handling %s exception with message "%s" in %s' % \
(exc_type.__name__, exc_value, threading.current_thread().name))
class ConsumerThread(threading.Thread):
def __init__(self, queue, *args, **kwargs):
super(ConsumerThread, self).__init__(*args, **kwargs)
self._queue = queue
def run(self):
bigchaindb = bigchain.BigChain()
bdb = bigchaindb.connect('localhost', 3277)
keys = bigchaindb.loadkeys()
rabbit = rabbitMq.RabbitMq(self._queue, bdb, keys)
channel = rabbit.connect()
while True:
try:
rabbit.consume(channel)
# raise RuntimeError('This is the error message')
except:
do_something_with_exception()
break
if __name__ == "__main__":
threads = [ConsumerThread("sms"), ConsumerThread("contract")]
for thread in threads:
thread.daemon = True
thread.start()
for thread in threads:
thread.join()
exit(1)
謝謝,這清除了如何定義異常! –