Python线程Catch异常和退出

时间:2017-09-04 18:35:17

标签: python python-3.x python-multithreading

我是Python Development的新手,并试图找出如何捕获线程中的ConnectionError,然后退出。目前我有它所以它可以捕获一般异常但我想为不同的异常指定不同的异常处理,并且还停止应用程序对某些类型的异常。

我目前正在使用线程,但我开始怀疑我是否应该使用多线程?

以下是代码的副本:

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)

1 个答案:

答案 0 :(得分:2)

Python有Built-in Exceptions。阅读每个异常描述以了解要引发的特定类型的异常。

例如:

raise ValueError('A very specific thing you don't want happened')

像这样使用它:

try:
    #some code that may raise ValueError
except ValueError as err:
    print(err.args)

这是Python异常层次结构列表:

 BaseException
... Exception
...... StandardError
......... TypeError
......... ImportError
............ ZipImportError
......... EnvironmentError
............ IOError
............... ItimerError
............ OSError
......... EOFError
......... RuntimeError
............ NotImplementedError
......... NameError
............ UnboundLocalError
......... AttributeError
......... SyntaxError
............ IndentationError
............... TabError
......... LookupError
............ IndexError
............ KeyError
............ CodecRegistryError
......... ValueError
............ UnicodeError
............... UnicodeEncodeError
............... UnicodeDecodeError
............... UnicodeTranslateError
......... AssertionError
......... ArithmeticError
............ FloatingPointError
............ OverflowError
............ ZeroDivisionError
......... SystemError
............ CodecRegistryError
......... ReferenceError
......... MemoryError
......... BufferError
...... StopIteration
...... Warning
......... UserWarning
......... DeprecationWarning
......... PendingDeprecationWarning
......... SyntaxWarning
......... RuntimeWarning
......... FutureWarning
......... ImportWarning
......... UnicodeWarning
......... BytesWarning
...... _OptionError
... GeneratorExit
... SystemExit
... KeyboardInterrupt

注意:SystemExit是一种特殊类型的异常。当提出Python解释器退出时;没有打印堆栈回溯。如果你没有指定异常状态,它将返回0。