简体   繁体   English

Python线程捕获异常并退出

[英]Python threading Catch Exception and Exit

I'm new to Python Development and trying to work out how to capture a ConnectionError within a thread, and then exit. 我是Python开发的新手,正在尝试弄清楚如何在线程中捕获ConnectionError,然后退出。 Currently I have it so it can catch a general exception but I would like to specify different exception handling for different exceptions, and also stop the application on certain types of Exception. 目前,我拥有它,因此它可以捕获一般的异常,但是我想为不同的异常指定不同的异常处理,并在某些类型的异常上停止应用程序。

I am currently using Threading, but I am starting to wonder if I should be using multithreading instead? 我当前正在使用线程,但是我开始怀疑是否应该使用多线程?

Here is a copy of the code: 这是代码的副本:

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)

Python has Built-in Exceptions . Python具有内置的Exception Read each exceptions description to know which specific type of exception you want to raise. 阅读每个异常描述,以了解您要提出哪种特定类型的异常。

For example: 例如:

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

use it like this: 像这样使用它:

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

here is a list of Python Exception Hierarchy: 以下是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

Note: SystemExit is a special type of exception. 注意:SystemExit是一种特殊的异常类型。 when raised Python interpreter exits; 当引发Python解释器退出时; no stack traceback is printed. 不打印堆栈回溯。 and if you don't specify the status of exception it will return 0. 如果您未指定例外状态,它将返回0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM