Nathan English
Nathan English

Reputation: 784

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. 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)

Upvotes: 0

Views: 2280

Answers (1)

OLIVER.KOO
OLIVER.KOO

Reputation: 5993

Python has Built-in Exceptions. 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:

 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. when raised Python interpreter exits; no stack traceback is printed. and if you don't specify the status of exception it will return 0.

Upvotes: 1

Related Questions